I have a SVG which can be zoomed and also a "reset" button. I'm resetting the zoom with
zoom.transform(selection, d3.zoomIdentity)
This works as expected and resets the zoom on the SVG. But if I zoom again, it zooms back to the last state. E.g. I scroll in, press "reset" button and then zoom out -> SVG is zoomed in. How can I reset the internal zoom state of the zoom
object? Tried out different solutions and none of them works.
Here the full zoom code
//zoom cannot be done on the <svg> directly
var container = d3.select("#g5063")
var zoom = d3.zoom().
scaleExtent([0.7, 8]).
on("zoom", () => {
container.attr("transform", d3.event.transform)
})
$("#reset-zoom-button").click(() => {
zoom.transform(container, d3.zoomIdentity);
})
var svg = d3.select("#svg").call(zoom)
I meet the same problem using
this.svg.selectAll('g').call(this.zoom.transform, d3.zoomIdentity.scale(1));
and I change to
this.svg.call(this.zoom.transform, d3.zoomIdentity.scale(1));
soloved the problem.
I think the _zoom
will be stored in the svg
level also.
This gist, which points to this working sample, ended up pointing me to the solution at least for my situation. As far as I can tell, it should fix your issue too.
What you're missing is that you need to tell zoomIdentity
what the initial x
, y
, and k
states should be. The x
and y
state is set using .translate(x,y)
and the scale is set using .scale(k)
. The code below should work.
$("#reset-zoom-button").click(() => {
zoom.transform(container, d3.zoomIdentity.translate(0,0).scale(0.7));
})
From what I can tell, translating the zoomIdentity
to 0,0 should always reset the svg to the initial settings position settings, but it's possible you'll have to play around with this.
Let me know if this works for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With