HTML5球体下落粒子爆炸特效
<!DOCTYPE html>
<html>
<head>
<title>球体爆炸特效</title>
<style>
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const width = canvas.width = window.innerWidth;
const height = canvas.height = window.innerHeight;
const particles = [];
const particleCount = 200;
const radius = 75;
const x = width / 2;
const y = height / 2;
class Particle {
constructor() {
this.x = x;
this.y = y;
this.vx = (Math.random() - 0.5) * 5;
this.vy = (Math.random() - 0.5) * 5;
this.radius = Math.random() * 2 + 1;
this.life = 1;
this.decay = Math.random() * 0.01 + 0.01;
}
update() {
this.x += this.vx;
this.y += this.vy;
this.life -= this.decay;
}
draw() {
ctx.beginPath();
ctx.globalAlpha = this.life;
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
ctx.fill();
}
}
function init() {
for (let i = 0; i < particleCount; i++) {
particles.push(new Particle());
}
animate();
}
function animate() {
ctx.clearRect(0, 0, width, height);
particles.forEach((particle) => {
particle.update();
particle.draw();
});
requestAnimationFrame(animate);
}
init();
</script>
</body>
</html>
这段代码使用了HTML5的canvas元素来创建一个球体下落并爆炸的粒子特效。它定义了一个Particle
类来表示每个粒子,并在init
函数中初始化了一系列粒子。animate
函数则负责更新和绘制每个粒子,从而形成动态的爆炸效果。这个示例展示了如何使用JavaScript和HTML5 canvas API创建简单的动画效果,对于学习基本的Web动画技术有很好的教育价值。
评论已关闭