当前位置:首页 > 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实现分页

实现分页的基本思路 分页功能通常需要处理数据分割、页码生成和用户交互。核心逻辑包括计算总页数、根据当前页截取数据、渲染页码按钮等。 前端分页实现(静态数据) 假设已有全部数据,仅需前端分页展示:…

js 实现继承

js 实现继承

原型链继承 通过让子类的原型对象指向父类的实例来实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Par…

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('image…

js实现复制到剪贴板

js实现复制到剪贴板

使用document.execCommand方法(传统方式,已废弃但部分浏览器仍支持) 该方法适用于旧版浏览器,但已被标记为废弃。执行前需确保文本已被选中: function copyToClipb…

js防抖和节流实现

js防抖和节流实现

防抖(Debounce)的实现 防抖的核心思想是在事件被触发后,延迟执行回调函数。如果在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口大小调整等场景。 function debounce…

js实现抽奖

js实现抽奖

实现抽奖功能的基本思路 抽奖功能的核心是随机选择奖项并展示结果。可以通过数组存储奖项,利用随机数生成索引,最后通过动画增强用户体验。 准备奖项数据 定义一个数组存储奖项信息,每个奖项可以包含名称、图…