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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值