直線運(yùn)動

<!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 = [];//用來存儲所有產(chǎn)生的對象
        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>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容