JavaScript is required

自定义线条动画1

沿线路径移动的动画元素

演示如何使用 CSS offset-path 在连线路上放置和动画化 DIV 元素移动,并自动更新路径。

沿线路径移动的动画元素

功能概述

此示例演示如何使用 CSS offset-path 在连线上放置 DIV 元素并使其沿线路径动画移动。该元素精确跟随连线,即使在拖动节点或连线形状改变时也是如此。

核心特性实现

CSS 偏移路径用于路径跟随

使用 CSS offset-path 属性使元素跟随特定路径:

const [divOffsetPath, setDivOffsetPath] = useState('');

// 当选中连线时设置 offset-path 样式
setDivOffsetPath(`path('${pathInfo.pathData}')`);

生成线路径数据

使用 graphInstance.generateLinePath() 获取连线的 SVG 路径数据:

const handleLineSelection = (line: RGLine) => {
    currentLineObject.current = line;
    const lineConfig = graphInstance.generateLineConfig(line);
    if (lineConfig) {
        const pathInfo = graphInstance.generateLinePath(lineConfig);
        setDivOffsetPath(`path('${pathInfo.pathData}')`);
    }
};

位置控制

使用 offsetDistance 控制元素沿路径的位置:

  • 留空以进行连续动画
  • 设置为百分比(例如 ‘50%’)以进行静态定位
<div
    className={`div-on-line ${divPosition !== '' ? 'div-on-line-stoped' : ''}`}
    style={{
        offsetDistance: divPosition !== '' ? divPosition : undefined
    }}
>
    <div>⛵️</div>
</div>

节点拖动时更新路径

拖动节点时重新计算路径以保持元素在连线上:

const onNodeDragEnd = (nodeObject: RGNode, $event: RGUserEvent) => {
    if (currentLineObject.current) {
        handleLineSelection(currentLineObject.current!);
    }
};

连线单击选择

通过单击选择连线并应用高亮:

const onLineClick = (lineObject: RGLine, linkObject: RGLink, $event: RGUserEvent) => {
    handleLineSelection(lineObject);
};

动态连线形状更改

允许更改连线形状并相应地更新路径:

const setNewLineShape = async (newShape: number) => {
    setLineShape(newShape);
    const lines = graphInstance.getLines();
    lines.forEach(line => {
        graphInstance.updateLine(line, { lineShape: newShape });
    });

    if (currentLineObject.current) {
        handleLineSelection(currentLineObject.current!);
    }
};

画布上方插槽

使用 RGSlotOnCanvasAbove 确保移动元素显示在图表上方:

<RelationGraph>
    <RGSlotOnCanvasAbove>
        <div style={{ '--checked-line-path': divOffsetPath }}>
            <div className="div-on-line">⛵️</div>
        </div>
    </RGSlotOnCanvasAbove>
</RelationGraph>

创意使用场景

  • 数据流可视化:动画显示数据包通过连接移动
  • 路线规划:显示车辆或对象沿路线行驶
  • 进度指示器:显示沿流程的进度
  • 数据包追踪:可视化穿越拓扑的网络数据包
  • 动画教程:引导用户沿图表中的特定路径