【问题标题】:How to reset zoom.transform after zooming without reseting selections in D3?缩放后如何重置 zoom.transform 而不重置 D3 中的选择?
【发布时间】:2021-12-29 16:22:58
【问题描述】:

所以我使用d3.zoom 并定义on 方法并将转换手动应用于不同的元素。但是当另一个平移/缩放发生时,它会从原始状态转换为当前状态。我希望它只给我从最后一个状态到当前状态。

例如:首先我放大视图,这给了我一个类似这样的转换:{x=0,y=0,k=2}。下一次,如果我向右平移视图,event 中的transform 对象是{x=2,y=0,k=2}。但我希望它给我{x=2,y=0,k=1}。所以我需要在不改变元素转换的情况下以某种方式将缩放重置为d3.zoomIdentity。我该怎么做?

下面是一个代码 sn-p 解释我想要什么:

d3.zoom().on("zoom", event => {
  console.log(event.transform); // {x=1, y=5, k=0.5}
  recalculateVertices(event.transform);
  recalculateEdges(event.transform);

  // Now I want to reset the transform of zoom to {x=0,y=0,k=1}
  // Something like this
  resetZoom(zoom);
  
  // So the next time again a zoom event occurs, it will give the 
  // event.transform as the transformation only from current state to that next state.
  // Instead of "from original state to current state". 
})

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    您可以在缩放回调结束时调用selection.call(zoom.transform, zoomIdentity)。为避免无限递归,如果缩放变换为标识,则可以跳过回调:

    d3.zoom().on("zoom", event => {
      // Do nothing if the transform is the zoom identity. This avoids 
      //    infinite recursion with the last line of this callback
      if(event.transform.toString() === zoomIdentity.toString()) {
           return
      }
      console.log(event.transform); // {x=1, y=5, k=0.5}
      recalculateVertices(event.transform);
      recalculateEdges(event.transform);
    
      // "selection" is the d3 selection that calls zoom
      // "zoom" is the zoom behavior that gets called in the selection
      // "zoomIdentity" is the identity transform {x: 0, y: 0, k: 1}
      //    that is imported from d3
      selection.call(zoom.transform, zoomIdentity)
      // To avoid recursion (because the method above will trigger this callback
      //    again), the callback starts with a condition to do nothing when the zoom is 
      //    the identity transform
    })
    

    您可能需要稍微重新排序代码以引用缩放和回调上的选择:

        const zoom = d3.zoom();
        const selection = ...;
        zoom.on('zoom', ...);
        selection.call(zoom);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-25
      • 2018-01-16
      • 2010-10-01
      • 1970-01-01
      • 2015-04-22
      • 2021-04-07
      • 1970-01-01
      • 2022-07-08
      相关资源
      最近更新 更多