用HTML5 + JavaScript实现下雪效果
    		       		warning:
    		            这篇文章距离上次修改已过438天,其中的内容可能已经有所变动。
    		        
        		                
                以下是一个简单的下雪效果实现,使用HTML5和JavaScript。
HTML部分(index.html):
<!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%;
  }
  canvas {
    display: block;
  }
</style>
</head>
<body>
<canvas id="snow-canvas"></canvas>
 
<script src="snow.js"></script>
</body>
</html>JavaScript部分(snow.js):
const canvas = document.getElementById('snow-canvas');
const ctx = canvas.getContext('2d');
 
const snowflakes = [];
const flakeCount = 200;
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
 
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
 
function init() {
  for (let i = 0; i < flakeCount; i++) {
    snowflakes.push({
      x: Math.random() * canvasWidth,
      y: Math.random() * canvasHeight,
      size: Math.random() * 10,
      speed: Math.random() * 2 + 1,
    });
  }
}
 
function animateSnow() {
  ctx.clearRect(0, 0, canvasWidth, canvasHeight);
 
  snowflakes.forEach((flake) => {
    flake.y += flake.speed;
    flake.x *= 0.98;
    ctx.fillStyle = 'white';
    ctx.beginPath();
    ctx.arc(flake.x, flake.y, flake.size, 0, Math.PI * 2);
    ctx.fill();
 
    if (flake.y > canvasHeight) {
      flake.y = 0;
      flake.x = Math.random() * canvasWidth;
    }
  });
}
 
function loop() {
  requestAnimationFrame(loop);
  animateSnow();
}
 
init();
loop();这段代码会在页面上创建一个<canvas>元素,并在其中绘制下雪的效果。每个雪花是一个圆形,它们随机生成位置和大小,并以随机速度下降。如果雪花移出底部,它们会重新生成在顶部。这个简单的下雪效果可以通过调整flakeCount来控制雪花的数量,以及通过修改Math.random()的范围来调整雪花的大小和速度。
评论已关闭