圣诞节代码html飘雪花
时间: 2023-12-08 19:03:02 浏览: 64
以下是基于HTML5 Canvas实现的圣诞节动态下雪页面雪花飘落代码,你可以将其嵌入到你的网页中,制作出圣诞节主题相关的各种网页特效。
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>圣诞节动态下雪页面</title>
<style>
body {
background-color: #1E90FF;
}
canvas {
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// 设置canvas宽高
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 雪花数量
var snowCount = 100;
// 雪花数组
var snows = [];
// 雪花类
function Snow() {
// 雪花半径
this.r = Math.random() * 4 + 1;
// 雪花位置
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
// 雪花速度
this.vx = Math.random() * 2 - 1;
this.vy = Math.random() * 2 + 1;
// 雪花颜色
this.color = "#fff";
}
// 生成雪花
function createSnow() {
for (var i = 0; i < snowCount; i++) {
snows.push(new Snow());
}
}
// 绘制雪花
function drawSnow() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < snowCount; i++) {
var snow = snows[i];
ctx.beginPath();
ctx.arc(snow.x, snow.y, snow.r, 0, Math.PI * 2);
ctx.fillStyle = snow.color;
ctx.fill();
}
}
// 更新雪花位置
function updateSnow() {
for (var i = 0; i < snowCount; i++) {
var snow = snows[i];
snow.x += snow.vx;
snow.y += snow.vy;
if (snow.x > canvas.width + snow.r || snow.x < -snow.r || snow.y > canvas.height + snow.r) {
snows[i] = new Snow();
}
}
}
// 动画循环
function loop() {
drawSnow();
updateSnow();
requestAnimationFrame(loop);
}
// 初始化
createSnow();
loop();
</script>
</body>
</html>
```