Moving Ball (canvas畫布移動的小球)

基於畫布canvas實現的小案例,監聽畫布上的鼠標移動事件,根據其座標繪製小球,實現小球的半徑的減小。顏色的隨機。

效果如下:
在這裏插入圖片描述
比較簡單,就不多說,直接上代碼了

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>MovingBall</title>
    <style>
        body {
            margin: 150px;
        }
    </style>
</head>

<body>

    <canvas id="mycanvas"></canvas>



    <script>
        let canvas = document.getElementById("mycanvas");
        let cxt = canvas.getContext("2d");
        canvas.width = 1000;
        canvas.height = 600;
        canvas.style.background = "#000";

        class Ball {
            /**
             *構造器
             */
            constructor(x, y, color) {
                    this.x = x;
                    this.y = y;
                    this.color = color;
                    this.r = 40;
                }
                /**
                 *繪製小球 
                 */
            render() {
                cxt.save() //保存
                cxt.beginPath();
                cxt.arc(this.x, this.y, this.r, 0, Math.PI * 2);
                cxt.fillStyle = this.color;
                cxt.fill()
                cxt.restore();
            }
        }

        class MoveBall extends Ball {
            constructor(x, y, color) {
                super(x, y, color);

                //位置和半徑的變化
                this.dX = Math.random(-5, 5);
                this.dY = Math.random(-5, 5);
                this.dR = Math.random(1, 4);
            }

            UpDate() {
                this.x += this.dX;
                this.y += this.dY;
                this.r -= this.dR;
                if (this.r < 0) {
                    this.r = 0;
                }
            }

        }
        let Balls = [];
        const colors = ['red', 'purple', 'green', 'orange', 'white', 'pick', 'blue', 'skyblue', 'yellow'];

        canvas.addEventListener('mousemove', (e) => {
            Balls.push(new MoveBall(e.offsetX, e.offsetY, colors[Math.floor(Math.random() * colors.length)]))
        })


        setInterval(() => {
            cxt.clearRect(0, 0, canvas.width, canvas.height);

            for (let i = 0; i < Balls.length; i++) {
                Balls[i].render();
                Balls[i].UpDate();
            }
        }, 50);
    </script>
</body>

</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章