简体   繁体   中英

Why doesn't this simple attrTween example work?

I'm trying to understand attrTween. I know the easy way to make this square move is just to use attr, but the purpose of the example is for me to understand attrTween. The following example doesn't do anything, but no js errors appear in the console either, so I'm not sure where I'm going wrong.

var svg = d3.select("svg")
var pi = Math.PI;

var mySquare=svg.append("rect")
  .attr("x",60)
  .attr("y",60)
  .attr("width",200)
  .attr("height",200);

mySquare.transition()
  .duration(2000)
  .attrTween("x", d3.interpolate(60,400))

And here's a livecoding link for the example: http://livecoding.io/5037197

From the API : "The return value [emphasis added] of tween must be an interpolator: a function..."

Here is one method, with an inline function.

http://jsfiddle.net/TsMgJ/2/

mySquare.transition()
  .duration(2000)
  .delay(500)
  .attrTween("x", function (d, i, a) { 
       console.log(a); // returns 60, the value of "x" at the start
       return d3.interpolate(a, 400); 
  });

And here is another method, with the function outside of the chaining.

http://jsfiddle.net/tz5KT/1/

mySquare.transition()
  .duration(2000)
  .delay(500)
  .attrTween("x", myTweenFunction ); 

function myTweenFunction(d, i, a) {
  console.log( a ); // returns 60, the current value (value at start)
  return d3.interpolate(a, 400);
}

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