需求:搜索某个节点,移动画布,至节点位于视图中心位置。
代码:
// 根据id定位到节点
const handleGotoNode: (id: string) => void = (id) => {
// 找到视口中心
const viewCenter = {
x: graph?.get('width') / 2,
y: graph?.get('height') / 2
};
const node = graph?.findById(id);
const modelCenter = graph?.getPointByCanvas(viewCenter.x, viewCenter.y);
if (node && modelCenter) {
const { x, y, width, height } = node.getBBox();
const scale = treeGraph.current?.getZoom() || 1
// 画布平移的目标位置,最终目标是graph.translate(dx, dy);
const dx = modelCenter.x - x;
const dy = modelCenter.y - y;
treeGraph.current?.translate((dx - width / 2) * scale, (dy - height / 2) * scale)
}
};
效果: