问题描述:
- 动态数据渲染过程,数据更新时图形位置偏移
- 拖拽后再次刷新数据位置变化
- 缩放后位置刷新一次位置变化一次
问题解决过程:
- TreeGraph,Api操作,使用graph.getGraphCenterPoint获取视图内容中心点,结合moveTo 结论:改变的是视图窗口的绝对坐标,无效果
- TreeGraph,Api操作,使用graph.getGraphCenterPoint获取视图内容中心点,结合translate 结论:改变的是视图窗口的相对坐标,无效果,发现getGraphCenterPoint获取视图内容中心点无法作为合适的前提坐标位点。
- graphRef.current.get('group').getMatrix(),获取头元素组矩阵,在数据刷新后再次获取最新头节点graphRef.current.get('group').getMatrix()矩阵,效果:能够实时刷新,且每次数据更新后会变回上次操作的位置,不足:功能满足但是每次更新数据会重新渲染,导致位置会出现偏移且性能不佳
- 最佳实现,结合useRef存储矩阵信息
代码:
useEffect(() => {
if (!graphRef.current) return;
graphRef.current.stopAnimate();
//记录初始偏移量
graphRef.current.on("dragEnd", (ev) => {
const matrix = graphRef.current?.get('group').getMatrix();
if (matrix) {
viewCenterRef.current = { x: matrix[6], y: matrix[7] };
}
})
const matrix = graphRef.current.get('group').getMatrix();
if (matrix) {
viewCenterRef.current = { x: matrix[6], y: matrix[7] };
}
//新数据触发前zoom值
const preZoom = graphRef.current.getZoom();
graphRef.current.changeData(prop.src);
if (preZoom && viewCenterRef.current) {
graphRef.current!.zoomTo(preZoom)
// 计算出相对偏移量并进行平移
const matrixAfterChangeData = graphRef.current.get('group').getMatrix();
const dx = viewCenterRef.current.x - matrixAfterChangeData[6];
const dy = viewCenterRef.current.y - matrixAfterChangeData[7];
graphRef.current.translate(dx, dy);
}
}, [prop.originSrc, graphRef.current]);
问题完美解决