要在网页上显示烟花效果,你可以使用 HTML 和 JavaScript。以下是一个简单的示例代码,使用 canvas
元素和一些 JavaScript 来创建烟花效果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>烟花效果</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: black;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="fireworksCanvas"></canvas>
<script>
const canvas = document.getElementById('fireworksCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function randomColor() {
return 'rgb(' + Math.floor(Math.random() * 256) + ',' +
Math.floor(Math.random() * 256) + ',' +
Math.floor(Math.random() * 256) + ')';
}
class Firework {
constructor(x, y) {
this.x = x;
this.y = y;
this.particles = [];
for (let i = 0; i < 100; i++) {
const angle = Math.random() * Math.PI * 2;
const speed = Math.random() * 5 + 1;
const color = randomColor();
this.particles.push({
x: x,
y: y,
vx: Math.cos(angle) * speed,
vy: Math.sin(angle) * speed,
color,
life: 100 // particle life duration
});
}
}
update() {
for (let particle of this.particles) {
particle.x += particle.vx;
particle.y += particle.vy;
particle.life--;
}
// Remove dead particles
this.particles = this.particles.filter(p => p.life > 0);
}
draw() {
for (let particle of this.particles) {
ctx.fillStyle = particle.color;
ctx.beginPath();
ctx.arc(particle.x, particle.y, 3, 0, Math.PI * 2);
ctx.fill();
}
}
}
let fireworks = [];
function loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (Math.random() < 0.05) { // Create a firework randomly
fireworks.push(new Firework(Math.random() * canvas.width, canvas.height));
}
for (let firework of fireworks) {
firework.update();
firework.draw();
// If there are no particles left in the firework
if(firework.particles.length === 0){
fireworks.splice(fireworks.indexOf(firework),1);
}
}
requestAnimationFrame(loop);
}
loop();
</script>
</body>
</html>
将以上代码保存为 index.html
文件并在浏览器中打开,就会看到随机生成的烟花效果。每个烟花会发射多个彩色粒子,随着时间推移逐渐消失。你可以根据需要调整参数以改变效果。
内容由零声教学AI助手提供,问题来源于学员提问