直线运动

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            #kk{
                box-shadow: 0 0 10px 0 sandybrown;
            }
        </style>
    </head>
    <body>
        <canvas id="kk" width="500" height="500"></canvas>
    </body>
    <script type="text/javascript">
        var myCanvas = document.getElementById("kk");
        var context = myCanvas.getContext("2d");
        
//      context.beginPath();
//      context.fillStyle = "red";
//      context.arc(100,100,30,0,Math.PI*2,false);
//      context.fill();
        
//      var ball = {
//          r:30,
//          x:100,
//          y:100,
//          color:"red",
//          speedX:3,
//          speedY:5
//      }
        function rand (min,max) {
            return parseInt(Math.random()*(max-min+1)+min)
        }
        function Ball () {
            this.r = rand(10,30);
            this.x = rand(this.r,myCanvas.width-this.r);
            this.y = rand(this.r,myCanvas.height-this.r);
            this.color = `rgb(${rand(0,255)},${rand(0,255)},${rand(0,255)})`;
            var rX = rand(-4,4);
            var rY = rand(-4,4);
            this.speedX = rX == 0?2:rX;
            this.speedY = rY == 0?1:rY;
        }
        
        Ball.prototype.draw = function () {
            context.beginPath();
            context.fillStyle = this.color;
            context.arc(this.x,this.y,this.r,0,Math.PI*2,false);
            context.fill();
        }
        Ball.prototype.move = function () {
            this.x+=this.speedX;
            this.y+=this.speedY;
            if(this.x+this.r>500 || this.x-this.r<0){
                this.speedX*=-1;
            }
            if(this.y+this.r>500 || this.y-this.r<0){
                this.speedY*=-1;
            }
        }
        var balls = [];//用来存储所有产生的对象
        for(var i=0;i<20;i++){
            var ball = new Ball();
            balls.push(ball);
        }

        function animate () {
            context.clearRect(0,0,myCanvas.width,myCanvas.height);
            for(var j=0;j<balls.length;j++){
                balls[j].draw();
                balls[j].move();
            }
            window.requestAnimationFrame(animate);
        }
        animate();
        
    </script>
</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容