两种雪花的动态效果代码,分别使用HTML/CSS和JavaScript实现

  1. 使用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个雪花,每个雪花都会沿着屏幕垂直方向下落。雪花的初始位置、下落速度和延迟时间都是随机的,以创建更自然的效果。你可以根据需要调整雪花的数量、大小和下落速度。

  1. 使用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>
  • 22
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值