跟小海一起看下雪——用HTML、CSS和JS实现简单的下雪特效
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>下雪特效</title>
<style>
body, html {
margin: 0;
padding: 0;
height: 100%;
}
#snow {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
</style>
</head>
<body>
<canvas id="snow"></canvas>
<script>
const canvas = document.getElementById('snow');
const ctx = canvas.getContext('2d');
const width = canvas.width = window.innerWidth;
const height = canvas.height = window.innerHeight;
const flakes = [];
const flakeCount = 200;
canvas.style.display = 'block';
function init() {
for (let i = 0; i < flakeCount; i++) {
flakes.push(new Flake());
}
animate();
}
function animate() {
ctx.clearRect(0, 0, width, height);
for (let i = 0; i < flakeCount; i++) {
flakes[i].update();
flakes[i].render(ctx);
}
requestAnimationFrame(animate);
}
function Flake() {
this.x = Math.random() * width;
this.y = Math.random() * height;
this.size = Math.random() * 2;
this.speed = Math.random() * 0.2 + 0.05;
this.speedY = Math.random() * 0.5 + 0.5;
}
Flake.prototype.update = function() {
this.x += Math.cos(this.speed);
this.y += this.speedY;
this.size = Math.random() * 2;
if (this.x > width || this.x < 0) this.x = Math.random() * width;
if (this.y > height) this.y = 0;
};
Flake.prototype.render = function(ctx) {
ctx.fillStyle = 'white';
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
};
init();
</script>
</body>
</html>
这段代码实现了简单的下雪效果。它首先设置了HTML和CSS,创建了一个<canvas>
元素,并通过JavaScript初始化了下雪的逻辑。代码中定义了Flake
对象来表示每一片雪花,并且在animate
函数中更新了每片雪花的位置和大小,实现了动态的下雪效果。
评论已关闭