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

如何基于react-particles实现鼠标跟随的单个粒子效果?

实现react-particles鼠标悬停跟随单个粒子的效果

要实现鼠标悬停时单个粒子跟随光标,无需使用会生成大量粒子的trail模式,可通过直接创建并控制单个粒子的位置来实现,具体方案如下:

实现步骤

  • 保存tsParticles容器引用,用于后续操作粒子
  • 初始化完成后创建一个静止粒子,标记唯一标识方便定位
  • 监听鼠标移动事件,实时更新该粒子的坐标
  • 组件卸载时清理事件监听

完整代码实现

import { useCallback, useEffect, useRef } from "react";
import Particles from "react-particles";
import { loadFull } from "tsparticles";

export default function App() {
  const containerRef = useRef(null);
  const followerParticleId = useRef(null);

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

  const particlesLoaded = useCallback(async (container) => {
    containerRef.current = container;
    
    // 创建单个跟随粒子:设置速度为0,保持静止状态
    const particle = await container.addParticle({
      position: { x: 0, y: 0 },
      velocity: { x: 0, y: 0 },
      color: { value: "#fff" },
      size: { value: 5 },
      opacity: { value: 1 },
      move: { enable: false } // 禁用粒子自身的移动逻辑
    });
    
    followerParticleId.current = particle.id;
  }, []);

  useEffect(() => {
    const handleMouseMove = (e) => {
      if (!containerRef.current || !followerParticleId.current) return;

      // 计算鼠标在粒子画布内的相对坐标
      const container = containerRef.current.canvas.element;
      const rect = container.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;

      // 定位目标粒子并更新其位置
      const particle = containerRef.current.particles.get(followerParticleId.current);
      if (particle) {
        particle.position.x = x;
        particle.position.y = y;
      }
    };

    window.addEventListener("mousemove", handleMouseMove);
    return () => window.removeEventListener("mousemove", handleMouseMove);
  }, []);

  return (
    <Particles
      id="tsparticles"
      init={particlesInit}
      loaded={particlesLoaded}
      options={{
        background: {
          color: { value: "#171717" }
        },
        fpsLimit: 120,
        interactivity: {
          events: {
            resize: true
          }
        },
        particles: {
          // 关闭默认粒子生成,只保留手动创建的跟随粒子
          number: { value: 0 },
          color: { value: "#aaa" },
          links: { enable: false },
          collisions: { enable: false },
          move: { enable: false }
        },
        detectRetina: true
      }}
    />
  );
}

关键代码说明

  1. 容器与粒子ID引用:通过containerRef保存tsParticles容器实例,followerParticleId存储手动创建的粒子ID,确保后续能精准定位目标粒子
  2. 创建静止粒子:在particlesLoaded回调中调用container.addParticle()生成粒子,设置move.enable: false和velocity: {x:0,y:0},让粒子保持静止不自主移动
  3. 鼠标位置同步:监听mousemove事件,计算鼠标在画布内的相对坐标,通过container.particles.get()获取目标粒子后直接更新其位置参数
  4. 默认粒子隐藏:将particles.number.value设为0,关闭默认粒子的链接、碰撞等功能,只保留手动创建的单个跟随粒子

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:17:48