Bootstrap

canvas实现小球自由落体

在上次代码里稍稍修改了一下也比较简单

 主要就是加了一个纵向加速度

 完整代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>阁下</title>
    <style>
        html,
        body {
            margin: 0;
            padding: 0;
            height: 100%;
            box-sizing: border-box;
        }
        #canvas {
            background-color: rgb(0, 0, 0);
        }
    </style>
</head>

<body>
    <canvas id="canvas"></canvas>
    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");

        function resizeFn(){
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
        }
        resizeFn();

        // 随机数
        function getRandom(min,max){
            return Math.floor(Math.random() * (max + 1 -min) + min);
        }

        class Point {
            constructor(){
                this.r = 12;//小球半径
                this.x = getRandom(0,canvas.width - this.r);//小球x坐标
                this.y = getRandom(0,canvas.height / 2);//小球y坐标
                this.ySpeed = 0;//y轴速度

                this.flag = null;
            }
            // 绘制单个小球
            draw(){
                if(this.flag){
                    //超出屏幕返回
                    this.ySpeed = this.ySpeed + 0.3;
                    this.y = this.y + this.ySpeed;
                    
                    if(this.y >=  canvas.height - this.r && Math.abs(this.ySpeed) <= 0.3) this.y = canvas.height - this.r;
                    // 加速度我设置的0.8
                    if(this.y + this.r + this.ySpeed + 0.3 >=  canvas.height) this.ySpeed *= -0.8;
                }
                // 绘制小球
                ctx.beginPath();getRandom
                ctx.arc(this.x,this.y,this.r,0,2 * Math.PI,false);
                ctx.fillStyle = `rgba(${getRandom(0,255)},${getRandom(0,255)},${getRandom(0,255)},1)`;
                ctx.fill();
                this.flag = true;
            }
        }

        // 更新
        class Update {
            //list 小球数量 distance 小球之间连线最大距离
            constructor(list = 30){
                this.arr = new Array(list).fill(0).map(() => new Point());
            }
            draw(){
                window.requestAnimationFrame(() => this.draw());
                ctx.clearRect(0,0,canvas.width,canvas.height);
                for(let i = 0;i<this.arr.length;i++){
                    // 绘制小球
                    this.arr[i].draw();
                }
            }
        } 

        const update = new Update();
        update.draw();
    </script>
</body>

</html>
;