动画 SVG 边缘
🌐 Animated SVG Edge
沿着边的路径动画化自定义 SVG 元素的边缘。该组件基于 动画化 SVG 元素示例。
🌐 An edge that animates a custom SVG element along the edge’s path. This component is based on the animating SVG elements example.
安装
在安装组件之前,务必遵循 先决条件 。
npx shadcn@latest add https://ui.reactflow.dev/animated-svg-edge1. Connect the component with your React Flow application.
import { Background, ReactFlow } from "@xyflow/react";
import { AnimatedSvgEdge } from "@/registry/components/animated-svg-edge";
const defaultNodes = [
{
id: "1",
position: { x: 200, y: 200 },
data: { label: "A" },
},
{
id: "2",
position: { x: 400, y: 400 },
data: { label: "B" },
},
];
const defaultEdges = [
{
id: "1->2",
source: "1",
target: "2",
type: "animatedSvgEdge",
data: {
duration: 2,
shape: "package",
path: "smoothstep",
},
} satisfies AnimatedSvgEdge,
];
const edgeTypes = {
animatedSvgEdge: AnimatedSvgEdge,
};
export default function App() {
return (
<div className="h-full w-full">
<ReactFlow
defaultNodes={defaultNodes}
edgeTypes={edgeTypes}
defaultEdges={defaultEdges}
fitView
>
<Background />
</ReactFlow>
</div>
);
}自定义形状
🌐 Custom shapes
你的目标是向模块中添加你自己的 SVG 形状。每个形状都应该是一个 React 组件,该组件接受一个名为 animateMotionProps 的属性,并返回一些 SVG。
🌐 It is intended that you add your own SVG shapes to the module. Each shape should
be a React component that takes one prop, animateMotionProps, and returns some
SVG.
你可以在一个单独的文件中定义这些形状,也可以在与边组件相同的文件中定义它们。为了使用它们,你需要将它们添加到 shapes 记录中,如下所示:
🌐 You can define these shapes in a separate file or in the same file as the edge
component. In order to use them, you need to add them to the shapes record like
so:
const shapes = {
box: ({ animateMotionProps }) => (
<rect width="5" height="5" fill="#ff0073">
<animateMotion {...animateMotionProps} />
</rect>
),
} satisfies Record<string, AnimatedSvg>;shapes 记录的键是边数据中 shape 字段的有效值:
🌐 The keys of the shapes record are valid values for the shape field of the
edge’s data:
const initialEdges = [
{
// ...
type: "animatedSvgEdge",
data: {
duration: 2,
shape: "box",
},
} satisfies AnimatedSvgEdge,
];如果你想渲染常规的 HTML 元素,请务必将它们封装在一个 SVG <foreignObject /> 元素中。确保给 <foreignObject /> 一个 id 属性,并在渲染 <animateMotion /> 元素时将其用作 href 属性。