HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Snowing Effect</title>
<style>
canvas {
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="snow.js"></script>
</body>
</html>
JS:
//配置选项
var CONFIG = {
maxSnowNum: 100, //最大雪花数量
snowColors: ['#FFF'], //雪花颜色
};
//创建画布
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//设置画布尺寸为窗口大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
//存储所有雪花
var snows = [];
//创建单个雪花对象
function createSnow() {
var snow = {};
//随机生成位置、半径、下落速度、颜色等属性值
snow.x = Math.random() * canvas.width; //横坐标随机生成
snow.y = -Math.random() * canvas.height; //纵坐标在顶部,所以取负数
snow.r = Math.random() * 4 + 1; //半径1-5px
snow.speed = Math.random() * 3 + 1; //下落速度1-4px
snow.color = CONFIG.snowColors[Math.floor(Math.random() * CONFIG.snowColors.length)]; //颜色
return snow;
}
//创建所有雪花
function createSnows() {
for (var i = 0; i < CONFIG.maxSnowNum; i++) {
snows.push(createSnow());
}
}
//更新单个雪花的位置和状态
function updateSnow(snow) {
snow.x += Math.random() - 0.5;
snow.y += snow.speed;
if (snow.x > canvas.width || snow.x < 0 ||
snow.y > canvas.height || snow.y < 0) {
//超出范围后重置到顶部继续下落
Object.assign(snow, createSnow());
}
}
//更新所有雪花的位置和状态
function updateSnows() {
snows.map(function(snow) {
updateSnow(snow);
});
}
//绘制单个雪花
function drawSnow(snow) {
ctx.beginPath();
ctx.arc(snow.x, snow.y, snow.r, 0, Math.PI * 2);
ctx.fillStyle = snow.color;
ctx.fill();
}
//绘制所有雪花
function drawSnows() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
snows.map(function(snow) {
drawSnow(snow);
});
}
//初始化
createSnows();
//开始动画循环
(function animate() {
requestAnimationFrame(animate);
updateSnows();
drawSnows();
})();
这是一个非常基础的下雪效果,你可以根据需要调整配置选项,例如添加不同形状、大小、速度的雪花等。