使用HTML/CSS实现雪花动态效果
html复制代码
<!DOCTYPE html> | |
<html> | |
<head> | |
<style> | |
.snowflake { | |
position: absolute; | |
top: 0; | |
background: white; | |
height: 5px; | |
width: 5px; | |
border-radius: 50%; | |
opacity: 0.7; | |
filter: blur(2px); | |
animation: fall linear infinite; | |
} | |
@keyframes fall { | |
to { | |
transform: translateY(100vh); | |
} | |
} | |
</style> | |
</head> | |
<body> | |
<div id="snowflakes"></div> | |
<script> | |
const snowflakesContainer = document.getElementById('snowflakes'); | |
const numberOfSnowflakes = 100; | |
for (let i = 0; i < numberOfSnowflakes; i++) { | |
const snowflake = document.createElement('div'); | |
snowflake.classList.add('snowflake'); | |
snowflake.style.left = `${Math.random() * 100}vw`; | |
snowflake.style.animationDuration = `${Math.random() * 3 + 2}s`; | |
snowflake.style.animationDelay = `${Math.random() * 5}s`; | |
snowflakesContainer.appendChild(snowflake); | |
} | |
</script> | |
</body> | |
</html> |
这段代码会在页面上生成100个雪花,每个雪花都会沿着屏幕垂直方向下落。雪花的初始位置、下落速度和延迟时间都是随机的,以创建更自然的效果。你可以根据需要调整雪花的数量、大小和下落速度。
使用JavaScript实现雪花动态效果(使用canvas)
html复制代码
<!DOCTYPE html> | |
<html> | |
<head> | |
<style> | |
canvas { | |
position: absolute; | |
top: 0; | |
left: 0; | |
} | |
</style> | |
</head> | |
<body> | |
<canvas id="snowCanvas"></canvas> | |
<script> | |
const canvas = document.getElementById('snowCanvas'); | |
const ctx = canvas.getContext('2d'); | |
const numberOfSnowflakes = 100; | |
const snowflakes = []; | |
class Snowflake { | |
constructor() { | |
this.x = Math.random() * canvas.width; | |
this.y = Math.random() * canvas.height; | |
this.size = Math.random() * 5 + 2; | |
this.speed = Math.random() * 1 + 0.5; | |
} | |
update() { | |
this.y += this.speed; | |
if (this.y > canvas.height) { | |
this.y = 0; | |
} | |
} | |
draw() { | |
ctx.beginPath(); | |
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2); | |
ctx.fill(); | |
} | |
} | |
function init() { | |
canvas.width = window.innerWidth; | |
canvas.height = window.innerHeight; | |
for (let i = 0; i < numberOfSnowflakes; i++) { | |
snowflakes.push(new Snowflake()); | |
} | |
animate(); | |
} | |
function animate() { | |
ctx.clearRect(0, 0, canvas.width, canvas.height); | |
snowflakes.forEach(snowflake => { | |
snowflake.update(); | |
snowflake.draw(); | |
}); | |
requestAnimationFrame(animate); | |
} | |
init(); | |
</script> | |
</body> | |
</html> |