canvas小球运动

标签: canvas

小球会不断往上冒


 

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>

    <body>
        <canvas id="canvas" width="1000" height="600" style="border: 1px solid red;"></canvas>
    </body>
    <script type="text/javascript">
        var canvas = document.getElementById('canvas');
        var ctx = canvas.getContext('2d');
        var raf;
        var _vx, x, y;
        class Ball {
            constructor() {
                this.radius = this.randomInt(30, 75)
                this.x = 500
                this.y = 650
                this.color = `rgba(${this.randomInt(100, 250)},${this.randomInt(100, 250)},${this.randomInt(0, 100)},${Math.random()})`
                
                this.speedX = this.randomInt(-3, 3) > 0 ? this.randomInt(-4, -1) : this.randomInt(1, 4)
                this.speedY = this.randomInt(0.3, 2)

            }
            draw() {
                ctx.beginPath();
                ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
                ctx.closePath();
                ctx.fillStyle = this.color;
                ctx.fill();
            }
            randomInt(from, to) {
                return parseInt(Math.random() * (to - from + 1) + from);
            }
            ballMove() {
                this.x += this.speedX;
                this.y -= this.speedY;

                if(this.x > 960) {
                    this.speedX *= -1
                }

                if(this.x < 25) {
                    this.speedX *= -1
                }

            }
        };

        //定义一个数组用来盛放所有的小球"对象"
        let balls = []
        let i = 1

        let ball = new Ball();
        balls.push(ball)
        setInterval(function() {
            i++;
            if(i % 30 == 0) {
                let ball = new Ball();
                balls.push(ball)
            }
            ctx.clearRect(0, 0, 1000, 600)
            for(let i = 0; i < balls.length; i++) {
                balls[i].ballMove();
                balls[i].draw()

            }
        }, 30)
    </script>

</html>

 

版权声明:本文为u013258556原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u013258556/article/details/102587012