html5下雪完整代码
时间: 2023-07-09 21:30:54 浏览: 50
下面是一个完整的 HTML、CSS、JavaScript 代码实现 HTML5 下雪效果的示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>HTML5 下雪效果</title>
<style>
body {
margin: 0;
padding: 0;
background-color: #000;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// 定义雪花类
var Snowflake = function(x, y, speed, size) {
this.x = x; // 雪花的 x 坐标
this.y = y; // 雪花的 y 坐标
this.speed = speed; // 雪花的下落速度
this.size = size; // 雪花的大小
};
// 绘制雪花
Snowflake.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = 'white';
ctx.fill();
};
// 更新雪花的位置
Snowflake.prototype.update = function() {
this.y += this.speed;
if (this.y > canvas.height + this.size) {
this.y = -this.size;
}
};
var snowflakes = []; // 存储所有雪花对象
// 创建多个雪花对象
for (var i = 0; i < 50; i++) {
var x = Math.random() * canvas.width;
var y = Math.random() * canvas.height;
var speed = Math.random() * 2 + 1;
var size = Math.random() * 4 + 2;
snowflakes.push(new Snowflake(x, y, speed, size));
}
// 定时更新雪花的位置,并重新绘制
setInterval(function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < snowflakes.length; i++) {
snowflakes[i].update();
snowflakes[i].draw();
}
}, 30);
</script>
</body>
</html>
```
在浏览器中打开该 HTML 文件,即可看到 HTML5 下雪效果。可以根据需要调整代码中的参数,实现不同的下雪效果。