实现Canvas粒子跟随鼠标移动的效果涉及到JavaScript和HTML5的Canvas API。下面是实现这一效果的基本步骤和代码示例。
基本步骤
创建Canvas:在HTML中添加一个
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas粒子跟随鼠标效果</title>
<style>
canvas {
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<canvas></canvas>
<script src="path/to/your/script.js"></script>
</body>
</html>
JavaScript
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let particles = [];
const numberOfParticles = 100;
let mouseX = 0;
let mouseY = 0;
class Particle {
constructor(){
this.x = mouseX;
this.y = mouseY;
this.size = Math.random() * 5 + 1;
this.speedX = Math.random() * 3 - 1.5;
this.speedY = Math.random() * 3 - 1.5;
}
update(){
this.x += this.speedX;
this.y += this.speedY;
if (this.size > 0.2) this.size -= 0.1;
}
draw(){
ctx.fillStyle = 'white';
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
}
}
const init = () => {
for (let i = 0; i < numberOfParticles; i++) {
particles.push(new Particle());
}
}
const animate = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particles.length; i++) {
particles[i].update();
particles[i].draw();
}
requestAnimationFrame(animate);
}
canvas.addEventListener('mousemove', (event) => {
mouseX = event.x;
mouseY = event.y;
particles.push(new Particle());
});
init();
animate();
在这个例子中,粒子在鼠标移动的地方生成,并以随机速度向四周扩散。Particle类代表了单个粒子,拥有位置、大小和速度属性。animate函数负责更新和绘制粒子。
自定义和优化
可以调整粒子的大小、颜色、速度和数量以获得不同的效果。
对于性能优化,可能需要限制粒子的总数量或当粒子超出屏幕时将其移除。
添加更多交互效果或不同的动画效果可以使得效果更加丰富。
以上代码提供了一个基本框架,你可以在此基础上进行修改和扩展,创造出独特的粒子效果。
版权属于:泽泽社长
本文链接:https://blog.zezeshe.com/archives/movement.html
本站未注明转载的文章均为原创,并采用
CC BY-NC-SA 4.0 授权协议,转载请注明来源,谢谢!