简体   繁体   中英

D3js zoom with reset function

I'm using D3js for a project and require the zooming function AND the ability to reset the zoom. My problem is that zooming functions act as if resets never happen. Here is the code I have:

function load() {
  var svg = d3.select("body")
    .append("svg")
    .attr("width", "100%")
    .attr("height", "100%");
  var zoom = d3.zoom().on("zoom", function() {
    d3.select("#vis").attr("transform", d3.event.transform);
  });
  var vis = svg.call(zoom).append("g").attr("id", "vis");
  d3.select("body").on("keypress", function() {
    if (d3.event.shiftKey) {                                                                                                        
      if (d3.event.key == "R") {                                                                                                    
        vis.transition().duration(500).attr("transform", d3.zoomIdentity);
      }
    }
  });
  vis.append("rect")
    .attr("x", 10)
    .attr("y", 10)
    .attr("width", 100)
    .attr("height", 100);
}

Here is a running example of the problem: http://bl.ocks.org/nicmcd/a74b0bfba61f50d932dedd6534ad7d9e

How can I get the reset action to reset the internal state of the zooming capability such that future events will base off the reset state?

There are two problems with my code. First, the transition needs to come from svg not vis . Second, the reset transform can't be done manually using attr() , it must be done using call() . Here is the revised code that works:

  function load() {
    var svg = d3.select("body")
      .append("svg")
      .attr("width", "100%")
      .attr("height", "100%");

    var zoom = d3.zoom().on("zoom", function() {
      vis.attr("transform", d3.event.transform);
    });

    var vis = svg.append("g").attr("id", "vis");
    svg.call(zoom);

    d3.select("body").on("keypress", function() {
      svg.transition().duration(500).attr("transform", d3.zoomIdentity)          
    });

    vis.append("rect")
      .attr("x", 10)
      .attr("y", 10)
      .attr("width", 100)
      .attr("height", 100);
  }

Here is a working example: http://bl.ocks.org/nicmcd/4c730aa64c04bf100a58f224b90c2ff4

Thanks to Andrew Reid for pointing out the errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM