当前位置:首页 > JavaScript

js实现雪花飘落

2026-01-30 14:25:09JavaScript

实现雪花飘落效果

使用JavaScript和CSS可以轻松实现雪花飘落效果。以下是两种常见方法:

使用Canvas绘制雪花

创建一个Canvas元素并绘制随机雪花:

js实现雪花飘落

<canvas id="snowCanvas"></canvas>
const canvas = document.getElementById('snowCanvas');
const ctx = canvas.getContext('2d');

// 设置canvas大小为窗口大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

// 雪花数组
const snowflakes = [];

// 创建雪花
class Snowflake {
  constructor() {
    this.x = Math.random() * canvas.width;
    this.y = Math.random() * canvas.height - canvas.height;
    this.radius = Math.random() * 4 + 1;
    this.speed = Math.random() * 3 + 1;
    this.wind = Math.random() * 0.5 - 0.25;
  }

  update() {
    this.y += this.speed;
    this.x += this.wind;

    // 雪花超出底部时重置到顶部
    if (this.y > canvas.height) {
      this.y = 0;
      this.x = Math.random() * canvas.width;
    }
  }

  draw() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
    ctx.fillStyle = 'white';
    ctx.fill();
  }
}

// 初始化雪花
for (let i = 0; i < 100; i++) {
  snowflakes.push(new Snowflake());
}

// 动画循环
function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  snowflakes.forEach(flake => {
    flake.update();
    flake.draw();
  });

  requestAnimationFrame(animate);
}

animate();

// 窗口大小改变时重置canvas大小
window.addEventListener('resize', () => {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
});

使用DOM元素实现雪花

创建多个div元素作为雪花并设置动画:

js实现雪花飘落

<div class="snow-container"></div>
.snow-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 100;
}

.snowflake {
  position: absolute;
  background-color: white;
  border-radius: 50%;
  pointer-events: none;
}
const container = document.querySelector('.snow-container');
const snowflakeCount = 50;

function createSnowflake() {
  const snowflake = document.createElement('div');
  snowflake.classList.add('snowflake');

  const size = Math.random() * 10 + 5;
  snowflake.style.width = `${size}px`;
  snowflake.style.height = `${size}px`;

  snowflake.style.left = `${Math.random() * 100}vw`;
  snowflake.style.top = `${Math.random() * -100}px`;

  const animationDuration = Math.random() * 10 + 5;
  snowflake.style.animation = `fall ${animationDuration}s linear infinite`;

  // 随机摆动效果
  snowflake.style.animation += `, sway ${animationDuration * 0.5}s ease-in-out infinite alternate`;

  container.appendChild(snowflake);

  // 雪花落地后移除
  setTimeout(() => {
    snowflake.remove();
    createSnowflake();
  }, animationDuration * 1000);
}

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
  @keyframes fall {
    to {
      transform: translateY(100vh);
    }
  }
  @keyframes sway {
    from {
      transform: translateX(0);
    }
    to {
      transform: translateX(50px);
    }
  }
`;
document.head.appendChild(style);

// 创建初始雪花
for (let i = 0; i < snowflakeCount; i++) {
  setTimeout(createSnowflake, Math.random() * 5000);
}

性能优化建议

对于大量雪花效果,Canvas实现性能更好。可以调整以下参数优化效果:

  • 减少雪花数量
  • 降低动画帧率
  • 使用requestAnimationFrame
  • 避免频繁DOM操作

添加交互效果

可以为雪花添加鼠标交互效果,例如鼠标经过时雪花避开:

document.addEventListener('mousemove', (e) => {
  const mouseX = e.clientX;
  const mouseY = e.clientY;

  snowflakes.forEach(flake => {
    const dx = flake.x - mouseX;
    const dy = flake.y - mouseY;
    const distance = Math.sqrt(dx * dx + dy * dy);

    if (distance < 50) {
      flake.x += dx / distance * 2;
      flake.y += dy / distance * 2;
    }
  });
});

以上代码提供了两种实现雪花飘落效果的方法,可根据项目需求选择适合的方案。Canvas版本适合复杂场景和大量粒子,DOM版本则更简单易于控制单个雪花样式。

标签: 雪花js
分享给朋友:

相关文章

js实现轮播

js实现轮播

实现基础轮播效果 使用HTML结构创建轮播容器和图片元素: <div class="carousel"> <div class="carousel-inner">…

js树实现

js树实现

树的基本概念 树是一种非线性的数据结构,由节点和边组成。每个节点包含一个值和指向子节点的引用。树的顶部节点称为根节点,没有子节点的节点称为叶节点。 树的实现方式 在JavaScript中,树可以通过…

js实现投球

js实现投球

实现投球动画的基本思路 使用JavaScript和CSS动画结合的方式模拟投球效果。核心是通过改变元素的位置、旋转和缩放属性,配合定时器或CSS过渡实现平滑动画。 创建基础HTML结构 <…

节流js实现

节流js实现

节流(Throttle)的实现原理 节流是一种限制函数执行频率的技术,确保函数在一定时间间隔内最多执行一次。适用于高频触发事件(如滚动、输入、窗口调整等)的场景。 基础实现方式 使用时间戳判断是否执…

js实现图片

js实现图片

图片加载与显示 在JavaScript中,可以通过Image对象动态加载图片。创建实例后设置src属性触发加载,通过onload回调处理加载完成后的操作: const img = new Ima…

js实现原理

js实现原理

JavaScript 实现原理 JavaScript 是一种解释型语言,其实现原理涉及多个核心组件和运行机制,包括引擎、运行时环境、事件循环等。 引擎与解释执行 现代 JavaScript 引擎(如…