跨年代码 烟花代码html
时间: 2023-06-17 18:03:33 浏览: 124
以下是一个简单的 HTML 网页,其中包含烟花效果的代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>跨年烟花</title>
<style>
body {
background-color: black;
color: white;
font-family: Arial, sans-serif;
text-align: center;
}
#fireworks {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
z-index: -1;
}
</style>
</head>
<body>
<h1>Happy New Year!</h1>
<canvas id="fireworks"></canvas>
<script>
// 烟花效果代码
var canvas = document.getElementById("fireworks");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext("2d");
var fireworks = [];
var particles = [];
function Firework() {
this.x = canvas.width / 2;
this.y = canvas.height;
this.color = "#" + ((1 << 24) * Math.random() | 0).toString(16);
this.radius = 2;
this.velocity = Math.random() * 6 + 3;
this.angle = Math.random() * Math.PI * 2;
this.acceleration = 1.05;
this.done = false;
this.update = function() {
this.velocity *= this.acceleration;
this.x += Math.cos(this.angle) * this.velocity;
this.y -= Math.sin(this.angle) * this.velocity;
if (this.velocity <= 1) {
this.done = true;
createParticles(this.x, this.y, this.color);
}
this.draw();
}
this.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
}
}
function Particle(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.radius = Math.random() * 3 + 1;
this.velocity = {
x: Math.random() * 6 - 3,
y: Math.random() * 6 - 3
};
this.acceleration = 0.95;
this.timeToLive = 100;
this.update = function() {
this.velocity.x *= this.acceleration;
this.velocity.y *= this.acceleration;
this.x += this.velocity.x;
this.y += this.velocity.y;
this.timeToLive--;
this.draw();
}
this.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
}
}
function createParticles(x, y, color) {
for (var i = 0; i < 30; i++) {
particles.push(new Particle(x, y, color));
}
}
function animate() {
ctx.fillStyle = "rgba(0, 0, 0, 0.4)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
if (Math.random() < 0.03) {
fireworks.push(new Firework());
}
for (var i = 0; i < fireworks.length; i++) {
fireworks[i].update();
if (fireworks[i].done) {
fireworks.splice(i, 1);
}
}
for (var i = 0; i < particles.length; i++) {
particles[i].update();
if (particles[i].timeToLive <= 0) {
particles.splice(i, 1);
}
}
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
```
你可以将这段代码复制到一个 HTML 文件中,然后在浏览器中打开它,就可以看到烟花效果了!
阅读全文