react激光如何使用
安装 react-laser 库
在项目中安装 react-laser 库,可以通过 npm 或 yarn 完成安装:
npm install react-laser
# 或
yarn add react-laser
导入组件
在需要使用激光效果的 React 组件中导入 Laser 组件:
import { Laser } from 'react-laser';
基本用法
将 Laser 组件添加到渲染部分,通过 points 属性传递激光路径的坐标点数组:
function App() {
const points = [
{ x: 100, y: 100 },
{ x: 200, y: 200 },
{ x: 300, y: 150 }
];
return (
<div>
<Laser points={points} color="red" width={2} />
</div>
);
}
动态更新路径
通过状态管理动态更新激光路径,例如结合鼠标移动事件:
import { useState } from 'react';
function App() {
const [points, setPoints] = useState([]);
const handleMouseMove = (e) => {
setPoints(prev => [...prev, { x: e.clientX, y: e.clientY }]);
};
return (
<div onMouseMove={handleMouseMove} style={{ height: '100vh' }}>
<Laser points={points} color="blue" width={3} />
</div>
);
}
自定义样式
通过 color 和 width 属性调整激光的颜色和宽度:
<Laser
points={points}
color="#00ff00" // 绿色激光
width={5} // 更粗的线条
/>
动画效果
结合 requestAnimationFrame 或第三方动画库(如 framer-motion)实现动态激光效果:

import { useEffect, useState } from 'react';
function App() {
const [points, setPoints] = useState([]);
useEffect(() => {
const animate = () => {
setPoints(prev => {
const newPoint = {
x: Math.random() * window.innerWidth,
y: Math.random() * window.innerHeight
};
return prev.length > 10 ? [...prev.slice(1), newPoint] : [...prev, newPoint];
});
requestAnimationFrame(animate);
};
animate();
}, []);
return <Laser points={points} color="purple" width={4} />;
}
注意事项
- 确保父容器有明确的尺寸(如
height: 100vh),否则激光可能不可见。 - 高频更新路径时(如鼠标跟踪),需优化性能避免卡顿。
react-laser基于 SVG 实现,兼容现代浏览器,但在旧版本浏览器中可能需要 polyfill。






