JavaScript Canvas 实现鼠标跟随光效动画

作者:小圆点

时间:2026-10-24

浏览:101

本文介绍如何利用HTML5 Canvas和JavaScript实现鼠标移动时的光片跟随特效。通过监听鼠标坐标,动态创建并绘制圆形元素,利用requestAnimationFrame实现流畅动画,并在元素透明度低于阈值时自动移除,完成一个轻量级的交互视觉示例。

文章目录

Canvas鼠标跟随特效实现

本示例展示了如何使用Canvas技术实现鼠标跟随的视觉效果,提供完整代码供参考。

核心逻辑在于监听鼠标移动事件,并在鼠标轨迹上生成光片元素。

Canvas鼠标跟随特效实现


<!DOCTYPE html>
<html>

<head>
 <meta charset="UTF-8">
 <title></title>
 <style>
 body {
 margin: 0;
 overflow: hidden;
 }

 #canvas {
 background: #000;
 }
 </style>
</head>

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

 canvas.width = window.innerWidth;
 canvas.height = window.innerHeight;

 canvas.addEventListener('mousemove', function (e) {
 // 将对象push到数组中,画出来的彩色小点可以看作每一个对象中记录着信息 然后存在数组中
 circleList.push(new Circle(e.clientX, e.clientY));
 })

 //取x到y之间随机数:Math.round(Math.random()*(y-x)+x) 包括y
 function random(min, max) {
 return Math.round(Math.random() * (max - min) + min);
 }

 function Circle(x, y) {
 this.x = x;
 this.y = y;

 this.vx = (Math.random() - 0.5) * 3; //随机出来一个正数,或者负数。乘3是为了让速度变得大一点
 this.vy = (Math.random() - 0.5) * 3;

 this.color = 'rgb(' + random(0, 255) + ',' + random(0, 255) + ',' + random(0, 255) + ')';

 this.a = 1; // 初始透明度

 this.draw();
 }
 Circle.prototype = {
 draw() {
 context.beginPath();
 context.fillStyle = this.color;
 context.globalCompositeOperation = 'lighter';
 context.globalAlpha = this.a; //全局透明度
 context.arc(this.x, this.y, 30, 0, Math.PI * 2, false);
 context.fill();
 this.update();
 },
 update() {
 // 根据速度更新每一个小圆的位置
 this.x += this.vx;
 this.y += this.vy;
 this.a *= 0.98;
 }
 }

 function render() {
 //把原来的内容区域清除掉
 context.clearRect(0, 0, canvas.width, canvas.height);
 circleList.forEach(function (ele, i) {
 ele.draw();

 if (ele.a < 0.05) {
  circleList.splice(i, 1);
 }
 });

 requestAnimationFrame(render); //动画,会根据浏览器的刷新频率更新动画
 }
 render();
 </script>
</body>

</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章