You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS Particles粒子动画运行一段时间后速度异常过快求助

修复React-tsparticles粒子运行一段时间后速度骤增的问题

问题分析

你遇到的粒子速度突然飙升的问题,核心原因是浏览器标签页失焦后requestAnimationFrame暂停执行,重新激活时tsparticles会将这段休眠时间的动画帧一次性计算,导致粒子速度因时间差累积出现异常叠加。修改fpsLimit和speed无法解决这个时间累积的根本问题。

解决方案

以下是几个直接有效的修复步骤:

  • 开启页面失焦暂停动画:在粒子配置中添加pauseOnBlur: true,当页面失去焦点时自动暂停粒子动画,从根源避免时间差累积。
  • 限制碰撞速度增益:调整碰撞参数,避免粒子因多次弹性碰撞持续加速,可降低collisions.bounce的数值(默认1为完全弹性碰撞)。
  • 确保依赖版本匹配:确认react-tsparticles和tsparticles的版本一致,避免版本兼容引发的异常。

修改后的完整代码

import { useCallback } from "react";
import Particles from "react-tsparticles";
import { loadFull } from "tsparticles";

const Parlex = () => {
  const particlesInit = useCallback(async (engine) => {
    await loadFull(engine);
  }, []);

  const particlesLoaded = useCallback(async (container) => {}, []);

  return (
    <Particles
      id="tsparticles"
      init={particlesInit}
      loaded={particlesLoaded}
      options={{
        // 新增:页面失焦时暂停动画,避免时间累积
        pauseOnBlur: true,
        background: {
          color: {
            value: "#fff",
          },
        },
        fpsLimit: 30,
        interactivity: {
          events: {
            onHover: {
              enable: true,
              mode: "repulse",
            },
            resize: true,
          },
          modes: {
            push: {
              quantity: 4,
            },
            repulse: {
              distance: 200,
              duration: 0.4,
            },
          },
        },
        particles: {
          color: {
            value: "#4a58de",
          },
          links: {
            color: "#8150ed",
            distance: 150,
            enable: true,
            opacity: 0.3,
            width: 1,
          },
          collisions: {
            enable: true,
            // 调整碰撞弹性,降低速度增益
            bounce: 0.8
          },
          move: {
            directions: "none",
            enable: true,
            outModes: {
              default: "bounce",
            },
            random: false,
            speed: 2,
            straight: false,
          },
          number: {
            density: {
              enable: true,
              area: 800,
            },
            value: 80,
          },
          opacity: {
            value: 0.3,
          },
          shape: {
            type: "circle",
          },
          size: {
            value: { min: 1, max: 5 },
          },
        },
      }}
    />
  );
};

export default Parlex;

额外排查方向

如果以上修改后仍有异常,可以尝试:

  • 将loadFull替换为loadBasic(仅加载基础粒子功能,减少潜在模块冲突)
  • 关闭粒子碰撞功能(将collisions.enable设为false),验证是否为碰撞逻辑导致的速度异常

内容的提问来源于stack exchange,提问作者Saad Hisham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 01:37:47