烟花跨年倒计时html代码
时间: 2024-12-26 13:25:13 浏览: 218
### 实现烟花效果的跨年倒计时HTML代码
为了创建具有烟花效果的新年倒计时网页,可以组合使用HTML、CSS以及JavaScript来达成视觉上的吸引力。下面是一个简单的例子:
#### HTML部分
此段代码定义了基本结构并引入必要的样式表和脚本文件。
```html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>2024新年快乐</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="countdown"></div>
<script src="script.js"></script>
</body>
</html>
```
#### CSS部分
这部分负责设置页面的整体外观,包括背景颜色和其他元素的位置布局等属性。
```css
/* styles.css */
body {
background-color: black;
color: white;
text-align: center;
font-family: Arial, sans-serif;
}
#countdown {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 7em;
}
```
#### JavaScript部分
这段代码实现了动态更新的时间显示功能,并模拟了烟花爆炸的效果。
```javascript
// script.js
function updateCountdown() {
const newYear = new Date('January 1, 2024 00:00:00');
let now = new Date();
if (now >= newYear) {
document.getElementById('countdown').innerText = '新年快乐!';
createFirework(); // 当到达新年时触发一次烟花动画
setInterval(createFirework, 3000); // 每隔三秒再放一组烟花
} else {
let diff = Math.floor((newYear - now) / 1000);
let days = Math.floor(diff / (60 * 60 * 24));
let hours = ('0' + Math.floor((diff % (60 * 60 * 24)) / (60 * 60))).slice(-2);
let minutes = ('0' + Math.floor(((diff % (60 * 60)) / 60))).slice(-2);
let seconds = ('0' + ((diff % 60))).slice(-2);
document.getElementById('countdown').innerText = `${days}天 ${hours}:${minutes}:${seconds}`;
setTimeout(updateCountdown, 1000);
}
}
updateCountdown();
function createFirework() {
var canvas = document.createElement('canvas');
with(canvas.style){
position='fixed';
bottom=left=top=right='0px';
pointerEvents='none';
}
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d'), w = window.innerWidth, h = window.innerHeight;
function random(min,max){return min+(max-min)*Math.random()}
class Particle{
constructor(x,y,vx,vy,radius,color,alpha,lifetime){
this.x=x;this.y=y;this.vx=vx;this.vy=vy;this.radius=radius||random(1,3);
this.color=color||`hsl(${random(0,360)},99%,50%)`;
this.alpha=(alpha===undefined)?1:alpha;
this.lifetime=lifetime||random(50,150);
}
draw(){
ctx.globalAlpha=this.alpha;
ctx.beginPath();
ctx.arc(this.x,this.y,this.radius,0,Math.PI*2,false);
ctx.fillStyle=this.color;
ctx.fill();
}
move(){this.x+=this.vx;this.y+=this.vy;this.alpha-=.01;if(--this.lifetime<0)this.dead=true;}
}
function explode(x,y,n){
particles.push(...Array.from({length:n},()=>new Particle(
x,
y,
random(-1,1),
random(-2,-1),
null,
`rgba(${~~random(0,255)},${~~random(0,255)},${~~random(0,255)},1)`,
.9,
~~random(50,150)
))
)
}
let particles=[];
explode(w/2,h,.5e3);
function animate(){
requestAnimationFrame(animate);
ctx.clearRect(0,0,w,h);
[...particles].forEach(p=>{
p.draw();
p.move();
!p.dead || particles.splice(particles.indexOf(p),1);
});
}
animate();
}
```
上述代码展示了如何通过HTML、CSS和JavaScript构建一个带有烟花特效的新年前夕倒计时页面[^1]。
阅读全文