2024html新年烟花代码
时间: 2024-02-10 21:09:55 浏览: 63
2024年的HTML新年烟花代码可以通过使用HTML5的Canvas元素和JavaScript来实现。以下是一个简单的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>2024 New Year Fireworks</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
background-color: black;
}
</style>
</head>
<body>
<canvas id="fireworksCanvas"></canvas>
<script>
// 获取画布元素
var canvas = document.getElementById("fireworksCanvas");
var ctx = canvas.getContext("2d");
// 设置画布大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 定义烟花粒子对象
function Particle(x, y) {
this.x = x;
this.y = y;
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.color = getRandomColor();
this.radius = Math.random() * 3 + 1;
this.alpha = 1;
}
// 更新粒子位置和透明度
Particle.prototype.update = function() {
this.x += this.vx;
this.y += this.vy;
this.alpha -= 0.01;
};
// 绘制粒子
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.globalAlpha = this.alpha;
ctx.fill();
};
// 创建烟花
function createFirework() {
var x = Math.random() * canvas.width;
var y = canvas.height;
var particleCount = 100;
var particles = [];
for (var i = 0; i < particleCount; i++) {
var particle = new Particle(x, y);
particles.push(particle);
}
// 更新和绘制粒子
function updateParticles() {
for (var i = 0; i < particles.length; i++) {
particles[i].update();
particles[i].draw();
// 移除透明度小于等于0的粒子
if (particles[i].alpha <= 0) {
particles.splice(i, 1);
}
}
}
// 动画循环
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 创建烟花
createFirework();
// 更新和绘制粒子
updateParticles();
requestAnimationFrame(animate);
}
animate();
}
// 随机生成颜色
function getRandomColor() {
var letters = "0123456789ABCDEF";
var color = "#";
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
// 页面加载完成后开始绘制烟花
window.onload = function() {
createFirework();
};
</script>
</body>
</html>
```
这段代码使用Canvas元素创建了一个全屏的画布,并通过JavaScript实现了烟花效果。每个烟花由多个粒子组成,粒子具有随机的速度、颜色和大小。通过不断更新和绘制粒子,实现了烟花的动画效果。