这篇文章带大家一起设置鼠标跟随特效,实现以下效果:

设置鼠标跟随特效
首先设置鼠标跟随特效,将以下代码(AI就可以搞定)添加到文件footer.php中</body>前保存,该文件位于网站主题文件夹下,我的位于

代码:
<!-- 鼠标粒子跟随效果 -->
<canvas id="particle-canvas"></canvas>
<style>
#particle-canvas {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 9999;
}
</style>
<script>
const canvas = document.getElementById('particle-canvas');
const ctx = canvas.getContext('2d');
const particles = [];
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = Math.random() * 2 + 2;
this.speedX = Math.random() * 1 - 0.5;
this.speedY = Math.random() * 1 - 0.5;
this.life = 2;
}
update() {
this.x += this.speedX;
this.y += this.speedY;
this.life -= 0.01;
this.size *= 0.98;
}
draw() {
ctx.save();
ctx.globalAlpha = this.life;
ctx.fillStyle = '#E979FF';
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particles.length; i++) {
particles[i].update();
particles[i].draw();
if (particles[i].life <= 0 || particles[i].size <= 0.2) {
particles.splice(i, 1);
i--;
}
}
requestAnimationFrame(animate);
}
window.addEventListener('mousemove', (e) => {
for (let i = 0; i < 5; i++) {
particles.push(new Particle(e.clientX, e.clientY));
}
});
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
animate();
</script>
想要自行修改效果的,可以参考以下设置:
| 功能 | 实现方式 |
| 改变粒子颜色 | 修改 ctx.fillStyle = '#ffffff'; 为其他颜色 |
| 改变粒子数量 | 修改 for (let i = 0; i < 3; i++) 中的数字 |
设置鼠标跟随图片
下一步,添加鼠标跟随图片。
将以下代码(借鉴echeverra.cn博客)添加到header.php文件(也位于主题文件夹下)中<body>前样式中保存,如图:
/* 鼠标样式 */
body { cursor: url(https://abcb.top/wp-content/plugins/mouse/mouse.png), default; }
a:hover{cursor:url(https://abcb.top/wp-content/plugins/mouse/mouse-hover.png), pointer;}

至此,鼠标特效大功告成
(全文完)