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, // 每秒帧数限制为120fpsinteractivity: {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 && (<Particlesid="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
进行偏好配置。