JavaScript is required

自定义线条样式

高级线条样式与最短路径

演示最短路径计算、自定义箭头标记和动态视觉效果,用于关系分析。

高级线条样式与最短路径高亮

功能概述

此示例演示了高级线条样式技术,包括最短路径计算、自定义箭头标记和动态视觉效果。它自动高亮节点之间的路径以展示关系分析功能。

核心特性实现

1. 自定义箭头标记

为线条端点定义自定义 SVG 标记:

// MySvgDefs.tsx
<defs>
    <marker id="my-arrow-001" markerWidth="10" markerHeight="10" refX="5" refY="5">
        <path d="M0,0 L10,5 L0,10" fill="#00ced1" />
    </marker>
</defs>

// 使用
{
    id: 'line-18',
    from: 'c',
    to: 'm1',
    endMarkerId: 'my-arrow-001',
    startMarkerId: 'my-arrow-001-start',
    showStartArrow: true
}

2. 最短路径计算

使用实用工具函数实现最短路径算法:

const calcShortestPath = (fromId: string, toId: string, graphInstance, className) => {
    // 使用 Dijkstra 或 BFS 计算最短路径
    const path = findShortestPath(fromId, toId);

    // 高亮路径线条
    path.forEach(lineId => {
        const line = graphInstance.getLines().find(l => l.id === lineId);
        if (line) {
            graphInstance.updateLine(line, { className });
        }
    });

    // 高亮路径节点
    path.forEach(lineId => {
        const line = graphInstance.getLines().find(l => l.id === lineId);
        graphInstance.updateNode(line.from, { className: 'my-node-on-path' });
        graphInstance.updateNode(line.to, { className: 'my-node-on-path' });
    });
};

3. 双击节点选择

实现两次单击路径选择的状态跟踪:

const checkedNodeIdRef = useRef('');

const onNodeClick = (node: RGNode) => {
    if (checkedNodeIdRef.current) {
        if (checkedNodeIdRef.current === node.id) return;
        calcShortestPath(checkedNodeIdRef.current, node.id, graphInstance, itemsOnPathClassName);
        checkedNodeIdRef.current = '';
    } else {
        checkedNodeIdRef.current = node.id;
    }
};

4. 路径线条的视觉效果

将 CSS 动画应用于高亮的路径:

.my-line-class-10 {
    stroke: #00ff00;
    animation: pulse-current 1s infinite;
}

.my-line-class-12 {
    stroke: #0099ff;
    animation: flow-data 2s infinite linear;
}

5. 自动路径演示

使用随机节点自动演示路径查找:

const restartRandomPathTask = () => {
    clearInterval(playTimerRef.current);
    playTimerRef.current = setInterval(() => {
        const nodes = graphInstance.getNodes();
        const randomNode = nodes[Math.floor(Math.random() * nodes.length)];
        onNodeClick(randomNode);
    }, 800);
};

创意使用场景

  • 路线规划:在交通网络中可视化最佳路线
  • 网络分析:识别基础设施中的关键路径
  • 社交网络分析:查找人员之间的最短连接路径
  • 供应链优化:突出显示高效的交付路线
  • 知识图谱:显示概念关系和路径
  • 电路设计:可视化电子电路中的信号路径