canvas制作(小demo)---圆球碰壁反弹

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36818386/article/details/82758417

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        canvas
        {
            border: 2px dashed brown;
        }
    </style>
</head>
<body>
<canvas width="500", height="500", id="canvas"></canvas>
</body>
<script>
	var canvas = document.getElementById("canvas");
	var ctx = canvas.getContext("2d"); //创建一个画布

    function Ball(x, y, r, color)
    {
        this.x = x;
        this.y = y;
        this.r = r;
        this.color = color;

        this.dx = Math.random() * 10;
	    this.dy = Math.random() * 10;
        arr.push(this);
    }

    Ball.prototype.update = function ()
    {
        this.x += this.dx;
	    this.y += this.dy;

	    if(this.x > 500 - this.r || this.x < this.r)
        {
            this.dx = -this.dx;
        }

	    if(this.y > 500 - this.r || this.y < this.r)
	    {
		    this.dy = -this.dy;
	    }
    };

    Ball.prototype.render = function ()
    {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.r, 0, 7, false);
        ctx.fillStyle = this.color;
        ctx.fill();
    };

    var arr = [];
    setInterval(function ()
    {
    	ctx.clearRect(0, 0, 500, 500);

        for(var i = 0; i < arr.length; i++)
        {
        	arr[i].update();
        	arr[i].render();
        }
    },20);

    canvas.onmousedown = function (e) {
      new Ball(e.clientX, e.clientY, Math.random() *50, 'red');
    };
</script>
</html>

猜你喜欢

转载自blog.csdn.net/qq_36818386/article/details/82758417
今日推荐