粒子特效是一种常见的视觉效果,广泛应用于游戏、动画和网页设计中。下面是一个简单的粒子特效的JavaScript源码示例,使用了HTML5的Canvas API来绘制粒子。
粒子特效通常涉及创建大量的小对象(粒子),这些对象具有位置、速度、加速度等属性,并且会根据一定的物理规则进行运动和变化。
以下是一个简单的粒子系统示例,创建了一个基本的粒子爆炸效果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Particle Effect</title>
<style>
canvas {
display: block;
background: #000;
}
</style>
</head>
<body>
<canvas id="particleCanvas"></canvas>
<script>
const canvas = document.getElementById('particleCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = Math.random() * 5 + 1;
this.speedX = Math.random() * 3 - 1.5;
this.speedY = Math.random() * 3 - 1.5;
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
}
update() {
this.x += this.speedX;
this.y += this.speedY;
this.size -= 0.1;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
}
}
let particles = [];
function createParticles(e) {
for (let i = 0; i < 50; i++) {
particles.push(new Particle(e.x, e.y));
}
}
function handleParticles() {
for (let i = particles.length - 1; i >= 0; i--) {
particles[i].update();
particles[i].draw();
if (particles[i].size <= 0) {
particles.splice(i, 1);
}
}
}
canvas.addEventListener('mousemove', createParticles);
setInterval(handleParticles, 1000 / 60);
</script>
</body>
</html>
粒子特效是一种强大的视觉表现工具,通过合理的设计和优化,可以在多种场景下提供出色的视觉体验。上述示例代码提供了一个基础的起点,可以根据具体需求进一步扩展和定制。
领取专属 10元无门槛券
手把手带您无忧上云