D3 - Resetting an SVG object animation

后端 未结 1 916
天涯浪人
天涯浪人 2021-01-27 15:32

I\'m making a graph with interactive markers. Each marker begins along the side axis, and when clicked moves to its place along the line and grows in size. I got the icons to mo

相关标签:
1条回答
  • 2021-01-27 16:11

    You're attaching two different click handers -- the first one to move there and the second one to move back. The second one stays attached, i.e. after the icon has moved back, its click handler will move it to the same position (that's why it seems as if it isn't moving).

    You can do this more elegantly (and fix the problem) by setting the attribute values in the click handler dynamically based on the current values.

    var coal = svg.append("svg:image")
      .attr("xlink:href", "nouns/coal.svg")
      .attr("width", 35)
      .attr("height", 35)
      .attr("x", 10)
      .attr("y", 30)
      .on("click", function() {
        d3.select(this).transition()
          .attr("x", function() { return d3.select(this).attr("x") == 10 ? 80 : 10; })
          .attr("y", function() { return d3.select(this).attr("y") == 30 ? 150 : 30; })
          .attr("width", function() { return d3.select(this).attr("width") == 35 ? 70 : 35; })
          .attr("height", function() { return d3.select(this).attr("height") == 35 ? 70 : 35; })
          .duration(750);
      });
    

    It would be even more elegant to base the entire thing on data, i.e. have an array that contains two elements that define the positions and size and alternate between them. In this case, you could also use the usual D3 .data() pattern.

    0 讨论(0)
提交回复
热议问题