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: rgba(200, 247, 239,0.3);
        }
    </style>
</head>

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

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


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

        canvas.addEventListener("mousemove",(e) => {
            arr.push({
                x:e.clientX,
                y:e.clientY,
                r:2,
                ySpeed:getRandom(1,5),//小球纵轴方向移动的速度
                speed:Math.random() * 0.4 + 0.2,//小球半径变化的速度
                rMax:getRandom(8,12),//小球最大半径
            })
        })

        // 绘制
        function draw(item){
            ctx.beginPath();
            ctx.fillStyle = "rgba(230,241,247,1)";
            ctx.strokeStyle = "rgba(152,198,224,0.8)";
            ctx.arc(item.x,item.y,item.r,0,2 * Math.PI,false);
            ctx.fill();
            ctx.stroke();
        }
        // 更新
        function update(){
            if(arr.length == 0) return;
            arr.forEach((item,i) => {
                // 更新半径
                item.r = item.r + item.speed;
                if(item.r >= item.rMax) arr.splice(i,1);
                // 更新y轴位置
                item.y = item.y - item.ySpeed;
                if(item.y + item.r < 0) arr.splice(i,1);
                // 绘制更新后的小球
                if(item) draw(item);
            })
        }
      
        setInterval(() => {
            // 清空画布
            ctx.clearRect(0,0,canvas.width,canvas.height);
            update();
        },50)
        
    </script>
</body>

</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阁下呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值