<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snowfall Effect</title>
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<canvas id="snowfallCanvas"></canvas>
<script>
const canvas = document.getElementById('snowfallCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function createSnowflake() {
const size = Math.random() * 3 + 1;
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
const speedY = Math.random() * 3 + 1;
ctx.fillStyle = '#fff';
ctx.beginPath();
drawSnowflake(x, y, size);
ctx.fill();
return { x, y, size, speedY };
}
function drawSnowflake(x, y, size) {
const sides = 6; // Six edges to simulate a snowflake
const angle = (Math.PI * 2) / sides;
ctx.moveTo(x, y - size);
for (let i = 0; i < sides; i++) {
ctx.lineTo(
x + Math.cos(angle * i) * size,
y + Math.sin(angle * i) * size
);
}
ctx.closePath();
}
function animateSnowflakes(snowflakes) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
snowflakes.forEach((flake) => {
flake.y += flake.speedY;
ctx.beginPath();
drawSnowflake(flake.x, flake.y, flake.size);
ctx.fillStyle = '#ccc';
ctx.fill();
if (flake.y > canvas.height) {
flake.y = 0;
flake.x = Math.random() * canvas.width;
}
});
requestAnimationFrame(() => animateSnowflakes(snowflakes));
}
const snowflakes = Array.from({ length: 100 }, createSnowflake);
animateSnowflakes(snowflakes);
</script>
</body>
</html>
效果
雪花js特效