【问题标题】:D3.js how to create this zoom behavior?D3.js 如何创建这种缩放行为?
【发布时间】:2021-08-18 19:29:04
【问题描述】:

我希望我的图表的 xAxis 在使用鼠标滚轮进行缩放时表现得像这样。 预期行为:

我当前的缩放

const zoomExtent = [ [ 0, 0 ], [ innerWidth, innerHeight ] ]
const xScale = scaleUtc().domain(minMaxData).range([0, innerWidth])

const handleZoom  = ({ transform }) => {
  transform.rescaleX(xScale)
}

const zoomBehavior = zoom().scaleExtent([ 0.4, 4 ]).extent(zoomExtent).translateExtent(zoomExtent).on('zoom', handleZoom)

这是我的 d3 默认行为图表

我的问题:

  1. 如何始终将缩放焦点集中在右边缘(图表上的最新数据)而不是鼠标当前所在的位置?
  2. 如何防止 x 轴向右扩展导致我的最新数据(在右边缘)离开视口?

【问题讨论】:

    标签: javascript d3.js zooming


    【解决方案1】:

    这不是一个优雅的解决方案,但它确实有效。

    // check if wheeled
    const isWheeled = sourceEvent.type === 'wheel'
    
    // i need it to be infinite because i lazy load the older data.
    // there is no middle infinity.
    const zoomExtent = [ [ Infinity, 0 ], [ innerWidth, innerHeight ] ]
    
    // fix focal point at the innerwidth. using previous transform
    const tx = innerWidth - transform.invertX(innerWidth) * k
    const myZoom = zoomIdentity.translate(isWheeled ? tx : x, 0).scale(k)
    
    // prevent jumping when dragging
    sourceEvent.target.__zoom = myZoom
    
    // update scale
    const handleZoom  = ({ transform }) => {
      myZoom.rescaleX(xScale)
    }
    

    如果您有更好的解决方案,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多