Canvas面向对象躁动的小球

直接上代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>躁动的小球</title>
        <style type="text/css">
            #canvas {
                border: 1px solid;
            }
        </style>
    </head>
    <body>
        <canvas id="canvas" width="800px" height="600px">
            浏览器不支持!!!
        </canvas>
    </body>
    <script type="text/javascript">
        var canvas = document.querySelector("#canvas");
        var ctx = canvas.getContext("2d");
        function Ball () {
            this.radius = this._rand(10,50);
            this.cx = this._rand(this.radius,canvas.width-this.radius);
            this.cy = this._rand(this.radius,canvas.height-this.radius);
            this.speedX = this._rand(-3,3);
            this.speedY = this._rand(-3,3);
            this.color = "rgba("+this._rand(0,255)+","+this._rand(0,255)+","+this._rand(0,255)+","+Math.random()+")";
        }
        Ball.prototype.draw = function () {
            ctx.beginPath();
            ctx.arc(this.cx,this.cy,this.radius,0,Math.PI*2);
            ctx.fillStyle = this.color; 
            ctx.fill();
        }
        Ball.prototype.move = function () {
            if (this.cx+this.radius >= canvas.width || this.cx-this.radius <= 0) {
                this.speedX *= -1;
            }
            if (this.cy+this.radius >= canvas.height || this.cy-this.radius <= 0) {
                this.speedY *= -1;
            }
            this.cx += this.speedX;
            this.cy += this.speedY;
            //在这里调用绘制方法,之后可以直接调用move方法即可绘制
            this.draw();
        }
        
        Ball.prototype._rand = function (max,min) {
            return parseInt(Math.random()*(max-min)+min);
        }
        
        
        var balls = [];
        for (var i = 0;i < 30;i++) {
            var ball = new Ball();
            balls.push(ball);
        }
//      setInterval(function () {
//          ctx.clearRect(0,0,800,600);
//          for (var i = 0;i <balls.length;i++) {
//              balls[i].move();
//          }           
//      },10);

        function _run () {
            ctx.clearRect(0,0,800,600);
            for (var i = 0;i < balls.length;i++) {
                balls[i].move();
            }
            requestAnimationFrame(_run);
        }
        _run();
        
        
    </script>
</html>

该方法为第五种(构造函数+原型模式)创建的方式:即将数据声明到函数内部,将函数声明到函数的原型上~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容