D3 v4: Reset zoom state

前端 未结 5 1821
谎友^
谎友^ 2021-02-19 07:26

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 wor

5条回答
  •  萌比男神i
    2021-02-19 08:22

    I ended up with the same issue and solved it by changing to the following line.

    svg.call(zoom.transform, d3.zoomIdentity.scale(1));
    

    Here is the complete code.

    //zoom cannot be done on the  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(() => {
        svg.call(zoom.transform, d3.zoomIdentity.scale(1));
    })
    
    var svg = d3.select("#svg").call(zoom)
    

    Here is testable script.

    //zoom cannot be done on the  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(() => {
        svg.call(zoom.transform, d3.zoomIdentity.translate(250, 100).scale(1))
    })
    
    var svg = d3.select("#svg").call(zoom)
    svg.call(zoom.transform, d3.zoomIdentity.translate(250, 100).scale(1))
    
    
    
      
        
      
    
    

提交回复
热议问题