一、基础概念
二、优势
三、类型
四、应用场景
五、常见问题及解决方法
以下是一个简单的使用Canvas API创建圆形粒子特效的JavaScript示例代码:
// 获取Canvas元素和上下文
const canvas = document.getElementById('particleCanvas');
const ctx = canvas.getContext('2d');
// 粒子类
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.vx = Math.random() * 2 - 1;
this.vy = Math.random() * 2 - 1;
this.radius = Math.random() * 3 + 1;
this.color = `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, 0.7)`;
this.life = Math.random() * 100 + 50;
}
update() {
this.x += this.vx;
this.y += this.vy;
this.life--;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
ctx.fillStyle = this.color;
ctx.fill();
}
}
// 创建粒子数组
let particles = [];
for (let i = 0; i < 100; i++) {
particles.push(new Particle(canvas.width / 2, canvas.height / 2));
}
// 动画循环
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach((particle, index) => {
particle.update();
particle.draw();
if (particle.life <= 0) {
particles.splice(index, 1);
particles.push(new Particle(canvas.width / 2, canvas.height / 2));
}
});
requestAnimationFrame(animate);
}
animate();
在这个示例中:
Particle
类,它包含了粒子的位置、速度、半径、颜色和生命周期等属性,以及更新粒子状态和绘制粒子的方法。领取专属 10元无门槛券
手把手带您无忧上云