canvas实现鼠标粒子随机运动

效果展示:

源码展示:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>canvas实现鼠标粒子随机运动</title>

    <style>
        * {
            margin:0;
        }
        canvas {
            background:#cccccc;
            margin:0 auto;
            display:block;
        }
    </style>
</head>
<body>
<canvas id="lizi" width="1000" height="1000"></canvas>

<script>
    window.onload = function() {
        let canvas = document.querySelector("#lizi");
        let cobj = canvas.getContext("2d");
        let x = 500;
        let y = 10;
        canvas.onmousemove = function(e) {
            x = e.offsetX
            y = e.offsetY;
        }

        class lizi {
            constructor(canvas, cobj) {
                this.canvas = canvas;
                this.cobj = cobj;
                this.r = 10 * Math.random();
                this.x = x;
                this.y = y;
                this.speedX = 6 * Math.random() - 2;
                this.speedY = -5;
                this.g = 0.3;
                this.color = `rgb(${parseInt(255*Math.random())},${parseInt(255*Math.random())},${parseInt(255*Math.random())})`
            }
            draw() {
                this.cobj.save();
                this.cobj.beginPath();
                this.cobj.translate(this.x, this.y);
                this.cobj.arc(0, 0, this.r, 0, Math.PI * 2); //建路径 // Math.PI*2 == 2π    // 0,Math.PI*2   从0到2π
                this.cobj.fillStyle = this.color;
                this.cobj.fill();
                this.cobj.restore();
            }
            updata() {
                this.x += this.speedX;
                this.speedY += this.g;
                this.y += this.speedY;
            }
        }



        let arr = [];
        let t = setInterval(function() {
            cobj.clearRect(0, 0, 1000, 1000);
            let liziobj = new lizi(canvas, cobj);
            arr.push(liziobj);
            for (let i = 0; i < arr.length; i++) {
                arr[i].draw();
                arr[i].updata();
            }
            if (arr.length >= 200) {
                arr.shift();
            }
        }, 50)
    }
</script>

</body>
</html>

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值