本文介绍了如何避免d3.zoom在第一次缩放或平移时转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试通过缩放和平移制作一个orgchart.为此,我需要调用.nodeSize,它将我的根"转换为(0,0).然后我将其重新按width/2转换,就可以了.但是当我实现d3.zoom时,我的根"回到(0,0)...如何避免这种行为?

I try to make an orgchart with zoom and paning. To do so I need to call .nodeSize which translate my "root" to (0,0). Then I re-translate it by width/2 and it's ok. But when I implement d3.zoom, my "root" go back to (0,0)... How can i avoid this behavior ?

有关代码如下:

var svg = d3.select("#svg1").append("svg")
  .attr("width", width)
  .attr("height", height)
  .call(d3.zoom().on("zoom", function () {
  svg.attr("transform", d3.event.transform);
  }))
  .append('g').attr("transform","translate(" + width / 2 + "," + 0 + ")");

感谢阅读.

我做了一个JSFiddle,所以您可以尝试一下我当前的代码.不要注意大的小方块(我的实际项目中没有它们)=> https://jsfiddle.net/rhz1n8m4/12/

EDIT : I did a JSFiddle so you can try my current code. Don't pay attention to big traingles (I don't have them on my real project) =>https://jsfiddle.net/rhz1n8m4/12/

推荐答案

将缩放应用于width/2变换下方的节点.

Apply the zoom to a node below the width/2 transform.

重命名您的变量以反映它们包含的内容:svg不包含svg元素.

Rename your vars to reflect what they contain: svg does not contain the svg element.

var svg = d3.select("#svg1").append("svg")
.attr("width", width)
.attr("height", height)
.call(d3.zoom().on("zoom", function () { svg.attr("transform", d3.event.transform); }))
.append('g').attr("transform","translate(" + width / 2 + "," + 0 + ")")
.append('g');

修改

@Zoom提出了使用transform-origin的解决方案(请参阅编辑历史记录),这显然是一种解决方法.最好重新安排g元素.

@Zoom proposed a solution with transform-origin (see edit history), clearly a workaround. Better is to re-arrange the g elements.

将缩放应用于width/2转换的上方节点.

Apply the zoom to a node above the width/2 transform.

  var svg1 = d3.select("#svg1")
    .append("svg")
      .attr("width", width)
      .attr("height", height)
    .call(d3.zoom().on("zoom", function () { svg1.attr("transform", d3.event.transform); }))
    .append('g');
  var svg = svg1.append('g')
      .attr("transform","translate(" + width / 2 + "," + 0 + ")");

阅读d3-zoom文档页面,您可能会发现不使用transform属性的其他解决方案.

Read the d3-zoom doc page and you might find a different solution that does not use a transform attribute.

这篇关于如何避免d3.zoom在第一次缩放或平移时转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 21:28