D3 - Resetting an SVG object animation

99封情书 提交于 2019-12-02 10:21:12

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!