react-tsparticles背景粒子闪烁及暗黑模式颜色切换问题求助
React-Tsparticles粒子闪烁及主题切换问题
我正在使用react-tsparticles开发背景效果,代码看似无错误,但运行时出现粒子反复显示消失的闪烁问题,同时希望点击暗黑模式按钮后粒子可切换颜色。
代码实现
Background.js
import ParticlesConfig from "./ParticlesConfig"; import { useCallback } from 'react'; import { loadFull } from 'tsparticles'; import Particles from 'react-tsparticles'; import React, { useEffect, useState } from "react"; const Background = (props) => { const [theme, setTheme] = useState("light"); const particlesInit = useCallback(async (engine) => { console.log(engine); // you can initiate the tsParticles instance (engine) here, adding custom shapes or presets // this loads the tsparticles package bundle, it's the easiest method for getting everything ready // starting from v2 you can add only the features you need reducing the bundle size await loadFull(engine); }, []); const [particlesContainer, setParticlesContainer] = useState(); const particlesLoaded = (container) => { setParticlesContainer(container); }; useEffect(() => { if (particlesContainer && particlesContainer.currentTheme !== props.theme) { particlesContainer.loadTheme(props.theme); } }, [props.theme, particlesContainer]); return ( <div id='particle-background'> <div className="background"> <button onClick={() => setTheme("light")}>Light</button> <button onClick={() => setTheme("dark")}>Dark</button> <Particles theme={theme} id='tsparticles' particlesLoaded='particlesLoaded' init={particlesInit} loaded={particlesLoaded} options={ParticlesConfig} /> </div> </div> ); }; export default Background;
ParticlesConfig.js
const ParticlesConfig = { autoplay: true, fullScreen: { enable: true, zIndex: 0, }, background: { color: { value: "transparent" } }, fpsLimit: 60, interactivity: { detect_on: 'window', events: { onClick: { enable: true, mode: "push" }, onHover: { enable: true, mode: "repulse" }, resize: true }, modes: { bubble: { distance: 400, duration: 2, opacity: 0.8, size: 40 }, push: { quantity: 1 }, repulse: { distance: 200, duration: 0.4 } } }, particles: { color: { value: "#777" }, links: { color: "#777777", distance: 150, enable: true, opacity: 0.5, width: 1 }, collisions: { enable: true }, move: { direction: "none", enable: true, outMode: "bounce", random: false, speed: 1, straight: false }, number: { density: { enable: true, area: 800 }, value: 90 }, opacity: { value: 0.5 }, shape: { type: "circle" }, size: { random: true, value: 5 } }, themes: [ { name: "light", default: { value: true, mode: "light" }, options: { background: { color: "#0f0e17" }, particles: { color: { value: "#ff8906" } } } }, { name: "dark", default: { value: true, mode: "dark" }, options: { background: { color: "transparent" }, particles: { color: { value: "#ff8906" } } } } ], detectRetina: true }; export default ParticlesConfig;
内容的提问来源于stack exchange,提问作者Doodzy
相关产品推荐
相关产品推荐

