import { useEffect, useRef } from 'react'; // 工具函数:合并 className(如果不需要可以删除,直接用 className) function cn(...inputs) { return inputs.filter(Boolean).join(' '); } /** * 流体背景动画组件 * @param {string} width - 容器宽度,默认 '400px' * @param {string} height - 容器高度,默认 '400px' * @param {number} speed - 动画速度倍数,默认 1.0 * @param {string} backgroundColor - 主背景颜色,默认 '#b6a9f8' * @param {string[]} colors - 圆形元素颜色数组(4个颜色),默认 ['#c979ee', '#ef788c', '#eb7fc6', '#6d67c8'] * @param {string[]} ringColors - 环形渐变颜色数组,默认 ['white', 'blue', 'magenta', 'violet', 'lightyellow'] * @param {string} className - 自定义 CSS 类名 */ const Spin = ({ speed = 1.0, backgroundColor = '#b6a9f8', colors = ['#c979ee', '#ef788c', '#eb7fc6', '#6d67c8'], ringColors = ['white', 'blue', 'magenta', 'violet', 'lightyellow'], className = '' }) => { const containerRef = useRef(null); useEffect(() => { // 注册 CSS @property(如果浏览器支持) if (CSS && CSS.registerProperty) { try { CSS.registerProperty({ name: '--a', syntax: '', inherits: true, initialValue: '0deg', }); CSS.registerProperty({ name: '--l', syntax: '', inherits: true, initialValue: '0', }); CSS.registerProperty({ name: '--x', syntax: '', inherits: false, initialValue: '0', }); CSS.registerProperty({ name: '--y', syntax: '', inherits: false, initialValue: '0', }); CSS.registerProperty({ name: '--o', syntax: '', inherits: false, initialValue: '0', }); CSS.registerProperty({ name: '--value', syntax: '', inherits: true, initialValue: '0deg', }); CSS.registerProperty({ name: '--width-ratio', syntax: '', inherits: true, initialValue: '0', }); CSS.registerProperty({ name: '--scale', syntax: '', inherits: true, initialValue: '0', }); } catch { // 浏览器不支持或已注册,忽略 } } }, []); // 使用 ResizeObserver 监听容器尺寸变化,动态更新 CSS 变量 useEffect(() => { const container = containerRef.current; if (!container) return; const updateSize = () => { const rect = container.getBoundingClientRect(); const size = Math.min(rect.width, rect.height); container.style.setProperty('--actual-size', `${size}px`); }; // 初始设置 updateSize(); // 使用 ResizeObserver 监听尺寸变化 const resizeObserver = new ResizeObserver(updateSize); resizeObserver.observe(container); return () => { resizeObserver.disconnect(); }; }, []); return ( <>
); }; export default Spin;