js实现爆炸
实现爆炸效果的 JavaScript 方法
使用 Canvas 绘制粒子爆炸效果
创建一个 Canvas 元素并初始化上下文,定义粒子对象数组,每个粒子包含位置、速度、大小和颜色等属性。
const canvas = document.getElementById('explosionCanvas');
const ctx = canvas.getContext('2d');
const particles = [];
function createExplosion(x, y) {
for (let i = 0; i < 100; i++) {
particles.push({
x,
y,
size: Math.random() * 5 + 2,
color: `hsl(${Math.random() * 60 + 20}, 100%, 50%)`,
speedX: Math.random() * 6 - 3,
speedY: Math.random() * 6 - 3,
life: 100
});
}
}
更新和渲染粒子
在动画循环中更新粒子位置并减少生命周期,移除死亡粒子,然后重新绘制所有粒子。
function updateParticles() {
for (let i = 0; i < particles.length; i++) {
const p = particles[i];
p.x += p.speedX;
p.y += p.speedY;
p.life--;
if (p.life <= 0) {
particles.splice(i, 1);
i--;
}
}
}
function drawParticles() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach(p => {
ctx.fillStyle = p.color;
ctx.beginPath();
ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
ctx.fill();
});
}
function animate() {
updateParticles();
drawParticles();
requestAnimationFrame(animate);
}
animate();
使用 CSS 动画实现视觉爆炸
创建爆炸元素和关键帧动画
定义 CSS 关键帧实现缩放和淡出效果,通过 JavaScript 动态创建爆炸元素并应用动画。
.explosion {
position: absolute;
width: 20px;
height: 20px;
border-radius: 50%;
pointer-events: none;
animation: explode 0.5s ease-out forwards;
}
@keyframes explode {
0% {
transform: scale(0);
opacity: 1;
}
100% {
transform: scale(10);
opacity: 0;
}
}
JavaScript 触发爆炸
function createCSSExplosion(x, y) {
const explosion = document.createElement('div');
explosion.className = 'explosion';
explosion.style.left = `${x}px`;
explosion.style.top = `${y}px`;
explosion.style.background = `hsl(${Math.random() * 360}, 100%, 50%)`;
document.body.appendChild(explosion);
explosion.addEventListener('animationend', () => {
explosion.remove();
});
}
document.addEventListener('click', (e) => {
createCSSExplosion(e.clientX, e.clientY);
});
物理引擎增强效果
使用 matter.js 实现物理爆炸
初始化物理引擎世界,创建圆形刚体并施加爆炸力。
const engine = Matter.Engine.create();
const world = engine.world;
const render = Matter.Render.create({
element: document.body,
engine: engine,
options: { width: 800, height: 600 }
});
function physicsExplosion(x, y, power) {
for (let i = 0; i < 20; i++) {
const particle = Matter.Bodies.circle(
x, y, Math.random() * 10 + 5,
{ restitution: 0.9, friction: 0.001 }
);
const force = {
x: (Math.random() - 0.5) * power,
y: (Math.random() - 0.5) * power
};
Matter.World.add(world, particle);
Matter.Body.applyForce(particle, particle.position, force);
}
}
Matter.Engine.run(engine);
Matter.Render.run(render);
document.addEventListener('click', (e) => {
physicsExplosion(e.clientX, e.clientY, 0.05);
});
性能优化建议
对于大量粒子场景,使用对象池技术重用粒子对象而非频繁创建销毁。考虑使用 WebGL 和 Three.js 实现更复杂的 3D 爆炸效果。降低非活动标签页的动画更新频率以节省资源。
const particlePool = [];
function getParticle() {
return particlePool.length ?
particlePool.pop() :
{ x: 0, y: 0, size: 0, color: '', speedX: 0, speedY: 0, life: 0 };
}
function recycleParticle(p) {
particlePool.push(p);
}






