Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 v4: Reset zoom state

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)
like image 900
ierqjirj13r109r1 Avatar asked Aug 08 '17 13:08

ierqjirj13r109r1


2 Answers

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.

like image 187
shenyu Avatar answered Oct 31 '22 19:10

shenyu


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.

like image 2
Austin A Avatar answered Oct 31 '22 17:10

Austin A