在react中使用Particles

step one

首先封装一个粒子效果组件,option各项配置在tsparticles/react 有介绍。

// ParticleBackground.js
import React, { useEffect, useState } from "react";
import { loadSlim } from "@tsparticles/slim";
import Particles, { initParticlesEngine } from "@tsparticles/react";

const ParticleBackground = React.memo(() => {
  const [init, setInit] = useState(false);

  const particlesOptions = {
    background: {
      color: {
        value: "FFB6C1", // 背景颜色设置
      },
    },
    fpsLimit: 120, // 每秒帧数限制为120fps
    interactivity: {
      events: {
        onClick: {
          enable: true, // 启用点击事件
          mode: "push", // 点击时推送粒子
        },
        onHover: {
          enable: true, // 启用悬停事件
          mode: "repulse", // 悬停时排斥粒子
        },
        resize: true, // 启用窗口大小调整事件
      },
      modes: {
        push: {
          quantity: 2, // 点击时添加的粒子数量
        },
        repulse: {
          distance: 80, // 悬停时排斥粒子的距离
          duration: 0.4, // 悬停排斥效果的持续时间
        },
      },
    },
    particles: {
      color: {
        value: "#ffffff", // 粒子颜色为白色
      },
      links: {
        color: "#ffffff", // 粒子连线颜色为白色
        distance: 150, // 粒子连线的最大距离
        enable: true, // 启用粒子连线
        opacity: 0.5, // 粒子连线透明度
        width: 1, // 粒子连线宽度
      },
      move: {
        direction: "none", // 粒子移动方向
        enable: true, // 启用粒子移动
        outModes: {
          default: "bounce", // 粒子碰到边界时反弹
        },
        random: true, // 粒子随机移动
        speed: 2.5, // 粒子移动速度
        straight: false, // 粒子不沿直线移动
      },
      number: {
        density: {
          enable: true, // 启用粒子密度计算
          area: 800, // 粒子活动区域面积
        },
        value: 180, // 粒子数量
      },
      opacity: {
        value: 0.5, // 粒子透明度
      },
      shape: {
        type: "circle", // 粒子形状为圆形
      },
      size: {
        value: { min: 1, max: 5 }, // 粒子大小范围
      },
    },
    detectRetina: true, // 启用视网膜屏优化
  };

  // 使用useEffect钩子初始化粒子效果引擎
  useEffect(() => {
    initParticlesEngine(async (engine) => {
      await loadSlim(engine);
    }).then(() => {
      setInit(true);
    });
  }, []);

  // 粒子效果容器加载回调
  const particlesLoaded = (container) => {
    // console.log(container);
  };

  return (
    <>
      {init && (
        <Particles
          id="tsparticles"
          particlesLoaded={particlesLoaded}
          options={particlesOptions}
        />
      )}
    </>
  );
});

ParticleBackground.displayName = "ParticleBackground";

export default ParticleBackground;

next

在组件中使用

import React from "react";
import ParticleBackground from "./ParticleBackground";
export default function demo() {
  return (
    <>
      <ParticleBackground />
    </>
  );
}

效果如下,可以通过option进行偏好配置。

posted @   烧邶  阅读(48)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示