html雪花漂落的代码
时间: 2023-12-22 07:28:09 浏览: 59
以下是一个简单的HTML雪花飘落特效的代码,使用了Canvas和JavaScript作画:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Snowfall Effect</title>
<style>
canvas {
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var w = canvas.width = window.innerWidth;
var h = canvas.height = window.innerHeight;
var count = 100; // 雪花数量
var snows = []; // 雪花数组
// 初始化雪花
for (var i = 0; i < count; i++) {
snows.push({
x: Math.random() * w, // 雪花的x坐标
y: Math.random() * h, // 雪花的y坐标
r: Math.random() * 5 // 雪花的半径
});
}
// 绘制雪花
function draw() {
ctx.clearRect(0, 0, w, h);
ctx.fillStyle = '#fff';
ctx.beginPath();
for (var i = 0; i < count; i++) {
var snow = snows[i];
ctx.moveTo(snow.x, snow.y);
ctx.arc(snow.x, snow.y, snow.r, 0, Math.PI * 2, true);
}
ctx.fill();
move();
}
// 移动雪花
function move() {
for (var i = 0; i < count; i++) {
var snow = snows[i];
snow.y += (7 - snow.r) / 10; // 从上往下飘落
snow.x += ((5 - snow.r) / 10); // 从左到右飘落
if (snow.y > h) {
snows[i] = {
x: Math.random() * w,
y: Math.random() * h,
r: Math.random() * 5,
};
}
}
}
// 循环绘制
setInterval(draw, 30);
</script>
</body>
</html>
```
阅读全文