雪花代码大全html
时间: 2023-12-25 11:29:33 浏览: 48
以下是一个在HTML中实现雪花飘落特效的代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>雪花飘落特效</title>
<style>
canvas {
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<canvas id="snowCanvas"></canvas>
<script>
var canvas = document.getElementById("snowCanvas");
var ctx = canvas.getContext("2d");
var w = window.innerWidth;
var h = window.innerHeight;
canvas.width = w;
canvas.height = h;
var count = 100; // 雪花数量
var snows = [];
// 初始化雪花
for (var i = 0; i < count; i++) {
snows.push({
x: Math.random() * w, // 随机横坐标
y: Math.random() * h, // 随机纵坐标
r: Math.random() * 5 // 随机半径
});
}
// 绘制雪花
function draw() {
ctx.clearRect(0, 0, w, h); // 清空画布
ctx.fillStyle = "#ffffff"; // 设置雪花颜色为白色
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();
}
// 移动雪花
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
};
}
}
}
// 动画循环
function animate() {
draw();
move();
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
```
这段代码使用了HTML的Canvas元素和JavaScript来实现雪花飘落的特效。首先,创建一个Canvas元素,并设置其宽度和高度为浏览器窗口的宽度和高度。然后,使用JavaScript初始化雪花的位置和半径,并在每一帧中绘制和移动雪花。最后,使用动画循环函数requestAnimationFrame来实现动画效果。