JavaScript 烟雾特效可以通过 HTML5 的 Canvas API 和 JavaScript 结合来实现。下面是一个简单的烟雾特效教程:
一、基础概念
烟雾特效通常是通过在屏幕上绘制一系列半透明的、逐渐扩散和淡化的圆形或粒子来模拟烟雾的效果。
二、优势
三、应用场景
四、实现步骤
<canvas id="smokeCanvas"></canvas>
const canvas = document.getElementById('smokeCanvas');
const ctx = canvas.getContext('2d');
class SmokeParticle {
constructor(x, y) {
this.x = x;
this.y = y;
this.vx = Math.random() * 2 - 1; // 水平速度
this.vy = Math.random() * -5 - 2; // 垂直速度
this.size = Math.random() * 3 + 1;
this.opacity = Math.random();
}
update() {
this.x += this.vx;
this.y += this.vy;
this.opacity -= 0.01;
}
draw(ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = `rgba(0, 0, 0, ${this.opacity})`;
ctx.fill();
}
}
const particles = [];
function createParticle() {
const x = canvas.width / 2;
const y = canvas.height;
particles.push(new SmokeParticle(x, y));
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach((particle, index) => {
particle.update();
if (particle.opacity <= 0) {
particles.splice(index, 1);
} else {
particle.draw(ctx);
}
});
requestAnimationFrame(animate);
}
setInterval(createParticle, 100);
animate();
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
五、可能遇到的问题及解决方法
这只是一个简单的示例,你可以根据实际需求进一步优化和扩展,比如添加风力影响、不同形状的粒子等。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云