Home > Net >  D3 zoom breaks mouse wheel zooming after using zoomIdentity
D3 zoom breaks mouse wheel zooming after using zoomIdentity

Time:11-11

When I use d3-zoom and programatically call the scaleTo function using zoomIdentity I cannot zoom using the mouse wheel anymore.

How do I fix this issue?

https://observablehq.com/d/8a5dfbc7d858a16b

// mouse wheel zoom not working because use of zoomIdentity

chart = {
  const svg = d3.create("svg")
      .attr("viewBox", [0, 0, width, height])
      .style("display", "block");

  const zoom = d3Zoom.zoom()
  svg.call(zoom);

  const zoomArea = svg.append('g');

  zoom.on('zoom', (e) => {
    zoomArea.attr("transform", e.transform)
  })


  zoomArea.append('circle')
    .attr("cx", width/2)
    .attr("cy", height/2)
    .attr("r", 20)
  
  zoom.scaleTo(svg, d3Zoom.zoomIdentity)

  return svg.node();
}

CodePudding user response:

The second parameter of zoom.scaleTo(svg, d3Zoom.zoomIdentity) accepts a k scaling factor (e.g., 2 for 2x zoom). The method zoom.scaleTo is intended to be used when you want to set the zoom level, but not the translation (x and y positions).

If you want to set the whole transform to the zoom identity (which resets both the zoom level and the x and y positions), the method is zoom.transform(svg, d3Zoom.zoomIdentity).

If you indeed just want to reset the scale, you can use zoom.scaleTo(svg, d3Zoom.zoomIdentity.k), or simply zoom.scaleTo(svg, 1).

  • Related