直接在HTML文件中添加以下代码即可实现圣诞下雪的效果:
<div id="snow-container">div>
在CSS文件中添加以下样式:
#snow-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 999999;
background-color: transparent;
background-image: url(snow.jpg);
background-position: center;
background-repeat: repeat;
}
在JavaScript文件中添加以下雪花效果代码:
var canvas = document.createElement("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.position = "fixed";
canvas.style.top = "0";
canvas.style.left = "0";
canvas.style.pointerEvents = "none";
canvas.style.zIndex = "99999";
document.getElementById("snow-container").appendChild(canvas);
var ctx = canvas.getContext("2d");
var snowflakes = [];
function Snowflake() {
this.x = Math.random() * window.innerWidth;
this.y = Math.random() * window.innerHeight;
this.vx = Math.random() * 2 - 1;
this.vy = Math.random() * 2 + 1;
this.radius = Math.random() * 5;
}
Snowflake.prototype.update = function () {
this.x += this.vx;
this.y += this.vy;
if (this.x > window.innerWidth || this.x < 0) {
this.vx *= -1;
}
if (this.y > window.innerHeight) {
this.y = 0;
}
};
Snowflake.prototype.render = function () {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = "#ffffff";
ctx.fill();
};
for (var i = 0; i < 100; i++) {
var snowflake = new Snowflake();
snowflakes.push(snowflake);
}
function animate() {
ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
for (var i = 0; i < snowflakes.length; i++) {
var snowflake = snowflakes[i];
snowflake.update();
snowflake.render();
}
requestAnimationFrame(animate);
}
animate();
暂无评论