跨年倒计时烟花html代码
时间: 2025-01-01 22:29:47 浏览: 9
### 跨年倒计时烟花效果 HTML 实现
为了创建一个具有跨年倒计时并伴有烟花动画效果的网页,可以采用HTML、CSS以及JavaScript相结合的方式。下面提供了一个完整的实例代码:
```html
<!DOCTYPE html>
<html lang="zh-8">
<title>新年快乐</title>
<style>
body {
background-color: black;
color: white;
text-align: center;
font-family: Arial, sans-serif;
}
.fireworks-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
overflow: hidden;
}
@keyframes explode {
from { transform: scale(0); opacity: 1;}
to { transform: scale(5); opacity: 0;}
}
.spark {
position: absolute;
border-radius: 50%;
animation-name: explode;
animation-duration: 1s;
animation-fill-mode: forwards;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>
</head>
<body>
<div id="countdown">距离新的一年还有...</div>
<div class="fireworks-container" id="fireworks"></div>
<script type="text/javascript">
// 设置目标时间为新年的零点时刻
var targetTime = new Date(new Date().getFullYear() + 1, 0, 1).getTime();
function updateCountdown() {
var currentTime = new Date().getTime();
var timeRemaining = Math.max(targetTime - currentTime, 0);
var days = Math.floor(timeRemaining / (1000 * 60 * 60 * 24));
var hours = Math.floor((timeRemaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);
document.getElementById('countdown').innerHTML =
"距离新的一年还有:" + days + "天 " + hours + "小时 "
+ minutes + "分钟 " + seconds + "秒 ";
if (timeRemaining === 0) {
clearInterval(intervalId);
showFireworks();
}
}
updateCountdown(); // 初始化显示一次剩余时间
var intervalId = setInterval(updateCountdown, 1000);
function createSpark(xPos, yPos, size, color) {
let sparkElement = document.createElement('div');
sparkElement.style.width = `${size}px`;
sparkElement.style.height = `${size}px`;
sparkElement.style.backgroundColor = color;
sparkElement.classList.add('spark');
sparkElement.style.left = xPos + 'px';
sparkElement.style.top = yPos + 'px';
anime({
targets: sparkElement,
translateX: function () {return anime.random(-window.innerWidth / 2, window.innerWidth / 2)},
translateY: function () {return anime.random(-window.innerHeight / 2, window.innerHeight / 2)},
easing: 'easeOutExpo',
duration: anime.random(700, 1300),
complete: function () {
sparkElement.remove();
}
});
document.querySelector('.fireworks-container').appendChild(sparkElement);
}
function showFireworks() {
const numSparks = 50;
for(let i=0;i<numSparks;i++){
setTimeout(() => {
createSpark(
anime.random(0, window.innerWidth),
anime.random(window.innerHeight / 2, window.innerHeight),
anime.random(10, 30),
`rgb(${anime.random(0, 255)}, ${anime.random(0, 255)}, ${anime.random(0, 255)})`
);
}, i*100);
}
}
</script>
</body>
</html>
```
此段代码通过设置`targetTime`变量来指定要倒数至的新的一年开始的时间戳,并利用定时器每秒钟更新一次页面上的倒计时时钟[^2]。
当到达设定的目标时间后,会触发`showFireworks()`函数执行一系列模拟烟花爆炸的效果。这些特效由多个随机位置和颜色的小圆圈组成,它们会在屏幕上迅速扩散开来形成绚丽多彩的画面效果。
阅读全文