以下是关于 JavaScript 触屏烟花特效的相关信息:
基础概念: 触屏烟花特效是通过 JavaScript 结合 HTML5 的 Canvas 或 WebGL 技术,在用户触摸屏幕时产生类似烟花绽放的视觉效果。
优势:
类型:
应用场景:
可能出现的问题及原因:
解决方法:
示例代码(简单的 2D 触屏烟花特效):
<canvas id="fireworkCanvas"></canvas>
<script>
const canvas = document.getElementById('fireworkCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
class Firework {
constructor(x, y) {
this.x = x;
this.y = y;
this.particles = [];
this.createParticles();
}
createParticles() {
for (let i = 0; i < 100; i++) {
const angle = Math.random() * Math.PI * 2;
const speed = Math.random() * 5;
const particle = {
x: this.x,
y: this.y,
vx: Math.cos(angle) * speed,
vy: Math.sin(angle) * speed,
color: `hsl(${Math.random() * 360}, 100%, 50%)`
};
this.particles.push(particle);
}
}
update() {
this.particles.forEach(particle => {
particle.x += particle.vx;
particle.y += particle.vy;
particle.vy += 0.1; // 模拟重力
});
}
draw() {
this.particles.forEach(particle => {
ctx.beginPath();
ctx.arc(particle.x, particle.y, 2, 0, Math.PI * 2);
ctx.fillStyle = particle.color;
ctx.fill();
});
}
}
let fireworks = [];
canvas.addEventListener('touchstart', (e) => {
e.preventDefault();
const touch = e.touches[0];
fireworks.push(new Firework(touch.clientX, touch.clientY));
});
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
fireworks.forEach((firework, index) => {
firework.update();
firework.draw();
if (firework.particles.every(particle => particle.y > canvas.height)) {
fireworks.splice(index, 1);
}
});
}
animate();
</script>
这段代码创建了一个简单的触屏烟花特效,在触摸屏幕时会产生烟花效果。
领取专属 10元无门槛券
手把手带您无忧上云