gpt4 book ai didi

javascript - 重新渲染图形时如何保持当前缩放比例和平移级别

转载 作者:行者123 更新时间:2023-12-03 06:16:15 25 4
gpt4 key购买 nike

我有一个 d3 图表,允许平移和缩放行为。它还具有子图功能,允许用户展开和折叠子图。当用户单击图标打开和关闭子图时,此代码将运行:

btn.on("click", function(d:any, i:any) {
parentNode = nodeObject; // gives me he x and y coordinates of the parent node
d3.event["stopPropagation"]();
e["subGraph"].expand = !expand; // add or remove subGraph

window.resetGraph = !window.resetGraph;
console.log(window.resetGraph);
if (window.resetGraph) {
window.scale = window.zoom.scale();
window.translate = window.zoom.translate();
window.zoom.scale(1).translate([0 , 0]);
} else {
window.zoom.scale(window.scale).translate(window.translate);
}

console.log(window.zoom.scale());
console.log(translate);

renderGraph();
});

我实际上是在单击图标时添加和删除节点的 subGraph 属性。然后完全重绘图表。

我可以获得父容器的 x 和 y 坐标,但如果我重新渲染图形,我该如何渲染图形,以便图形保持与我时相同的比例和平移单击切换子图图标。我试图在与之前相同的位置重新绘制图形,只是子图展开或折叠。下面是图表渲染时似乎在与我作斗争的代码:

   var scaleGraph = function() {
var graphWidth = g.graph().width + 4;
var graphHeight = g.graph().height + 4;
var width = parseInt(svg.style("width").replace(/px/, ""), 10);
var height = parseInt(svg.style("height").replace(/px/, ""), 10);
var zoomScale = originalZoomScale;
// Zoom and scale to fit
if (ctrl.autoResizeGraph === "original") {
zoomScale = initialZoomScale;
}


translate = [(width / 2) - ((graphWidth * zoomScale) / 2) + 2, 1];

zoom.center([width / 2, height / 2]);
zoom.size([width, height]);

zoom.translate(translate);
zoom.scale(zoomScale);

zoom.event(svg);
};

如果我检查切换图标是否已被单击,我可以使用与重绘之前相同的比例和平移来重绘图表吗?

谢谢

最佳答案

我刚刚通过跟踪当前的比例和平移值解决了这个问题:

  zoom.on("zoom", function() {
svgGroup.attr("transform", "translate(" + (<any>d3.event).translate + ")" + "scale(" + (<any>d3.event).scale + ")");

// keep track of the currentZoomScale and currentPosition at all times
currentZoomScale = (<any>d3.event).scale;
currentPosition = (<any>d3.event).translate;

});

然后,当在上面的scaleGraph函数中重新渲染图形时,我只是检查图形是否由于子图被切换而重新渲染,如果有,那么我使用当前的比例和平移值:

  if (ctrl.autoResizeGraph !== "original" && togglingSubGraph) {
zoomScale = currentZoomScale; // render the graph at its current scale
translate = currentPosition; // render the graph at its current position

}

关于javascript - 重新渲染图形时如何保持当前缩放比例和平移级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39090528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com