Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
841 views
in Technique[技术] by (71.8m points)

javascript - How to reset Zoom in d3.js?

I have a simple svg rectangle and I have added zooming and panning on it using d3.js. I have also added a button in order to try and reset the zoom once the button is clicked. Here is the code:

<button>Reset</button>
<body>
  <script>

      function zoomed() {
              svg.attr("transform", d3.event.transform)
      }

    var svg = d3.select("body")
      .append("svg")
      .attr("width", "100%")
      .attr("height", "100%")
      .call(d3.zoom().on("zoom", zoomed))
      .append("g")

    svg.append("rect")
        .attr("x", 450)
        .attr("y", 200)
        .attr("width", 300)
        .attr("height", 200)
        .style("fill", "#B8DEE6")

    $("#Reset").click(() => {
    zoom.transform(container, d3.zoomIdentity.scale(1));
})

  </script>
</body>

I have tried zoom.transform(container, d3.zoomIdentity.scale(1)) but it does not seem to work. Can anybody please tell what is the problem with the resetting function?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to rewrite your code this way:

function zoomed() {
  gElem.attr("transform", d3.event.transform)
}

var zoom = d3.zoom().on("zoom", zoomed);

var svg = d3.select("body")
  .append("svg")
  .attr("width", "600")
  .attr("height", "600")


var gElem = svg.append("g").call(zoom);

gElem.append("rect")
  .attr("x", 50)
  .attr("y", 50)
  .attr("width", 300)
  .attr("height", 200)
  .style("fill", "#B8DEE6")

$("#Reset").click(() => {
  gElem.transition()
    .duration(750)
    .call(zoom.transform, d3.zoomIdentity);
});

Check demo:

function zoomed() {
  gElem.attr("transform", d3.event.transform)
}

var zoom = d3.zoom().on("zoom", zoomed);

var svg = d3.select("body")
  .append("svg")
  .attr("width", "400")
  .attr("height", "200")
  

var gElem = svg.append("g").call(zoom);

gElem.append("rect")
  .attr("x", 50)
  .attr("y", 50)
  .attr("width", 300)
  .attr("height", 200)
  .style("fill", "#B8DEE6")

$("#Reset").click(() => {
  gElem.transition()
    .duration(750)
    .call(zoom.transform, d3.zoomIdentity);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="Reset">RESET</button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...