canvas鼠标在屏幕上的互动效果实现

这篇博客介绍了一个使用HTML5 Canvas实现的鼠标跟随动画,当鼠标移动时,会生成随机颜色和大小的圆圈,并逐渐增大直至消失,提供了一种动态视觉效果的实现方法。通过requestAnimationFrame实现平滑的动画效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.首先我们需要整屏画布(你也可以随机设置)

2.想要鼠标经过的时候有大小圆圈跟着鼠标动,故需要创建一个类来装圆的属性:随机的圆唯一的标识(id我这里用index),坐标(x, y),半径r,颜色color(因为要很多圆需要一个数组来装,上面变量中自行添加)

3.圆的所有属性有了,我想要把它画出来,故创建一个方法

 4.以上基本工作就做完了,因为我希望圆跟着我的鼠标运动,故需要过去鼠标移动过程中的坐标

5.接下来就需要做动画了,为了保证画面的流畅这里使用了requestAnimationFrame方法(备注很详尽)

 6.调用啊

 完整代码如下:

<!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>Document</title>
    <style>
        html, body {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            background: black;
        }
    </style>
</head>
<body>
    <canvas id="canvas"></canvas>
    <script>
        var ctx = document.getElementById('canvas')
            context = ctx.getContext('2d')
            Width = document.documentElement.clientWidth
            Height = document.documentElement.clientHeight
            ctx.width = Width
            ctx.height = Height
            color = 55
            rounds = []
        function Round_item (index, x, y, r, color) {
            this.index = index
            this.x = x
            this.y = y
            this.r = r
            this.color = 'hsl('+ color +',100%,80%)'
        }
        Round_item.prototype.draw = function () {
            context.fillStyle = this.color
            context.beginPath()
            context.arc(this.x, this.y, this.r, 0, 2*Math.PI, false)
            context.closePath()
            context.fill()
        }
        window.onmousemove = function (event) {
            rounds.push({
                x: event.clientX,
                y: event.clientY,
                r: 3,
            })
        }
        function animate () {
            // 清空画布
            context.clearRect(0, 0, Width, Height)
            for (let i = 0; i < rounds.length; i ++) {
                // 半径每次增大0.9
                rounds[i].r += 0.9
                // 由于hsl的颜色范围是1-360
                if (color > 360) {
                    color = 55
                }
                // 颜色变化
                color += 0.1
                rounds[i] = new Round_item(i, rounds[i].x, rounds[i].y, rounds[i].r, color)
                rounds[i].draw()
                // 圆的半径大于10就在下一次勾勒得时候消失
                if (rounds[i].r > 10) {
                    rounds.splice(i, 1)
                }
            }
            requestAnimationFrame(animate)
        }
        animate()
    </script>
</body>
</html>

 我学习的地址主要是菜鸟教程以及掘金,然后班门弄斧一下,有问题就指出哈,初学者一起加油

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值