Intro To D3, Transition Tween

While learning to use D3, I encountered difficulties understanding the basics of what a tween is, and how to implement it.

First, let’s look at this

This is an extremely helpful document, but can be overwhelming. So, let’s explore the very basic idea of tween:

Suppose a dot needs to move from point a to point b on the screen over some period of time. This dot has a starting (x,y) coordinate and an ending (x,y) coordinate. While the dot is moving it will be at a number of intermediate positions. These intermediate positions can be found by parameterizing with time, like so:

intermediateX(t) = startX + (endX - startX)*t
intermediateY(t) = startY + (endY - startY)*t

We can say that its intermediate position is a function of time, and is equal to its starting position plus time multiplied by the difference between its end position and starting position, where time is between zero and one.

intermediateX(0) = startX + (endX - startX)*0 = startX
intermediateX(1) = startX + (endX - startX)*1 = endX
intermediateY(0) = startY + (endY - startY)*0 = startY
intermediateY(1) = startY + (endY - startY)*1 = endY

So we see that as time goes from 0 to 1, the dot goes from its start to end.

How do we access all these intermediate positions? We can attach a custom tween function to a transition. This custom tween function must return a function. Inside the returning function, we are looking at a snapshot of the dot, during its transition.

d3Selection.transition().duration(n)
  .tween('custom', customTween);

var customTween = function() {
  return function(t){
    // everything in here is at a intermediate position and time
  };
}

It is important to note that the parameter t, input of the returning function, as well as the parameter we discussed above, is not actually time, it’s a parameter value between 0 and 1. It’s easy to imagine a transition that takes longer than 1 second, or shorter. So this time variable is simply a parameterization of the start/end time. At 0, the transition is starting; and at 1, the transition has just completed. How long this transition takes depends on the variable n in duration(n).

Usually, the object that is transitioning is of interest, so we might want to query it during the transition. We can do that by creating a closure scope prior to the returning function like this:

var customTween = function() {
  var obj = d3.select(this);
  return function(t) {
    // we can still access obj here, for example:
    console.log(obj);
  };
}

Hope that helps as an introduction to using tween for D3’s powerful transition function.

One last note, the t parameter in the returning function will only be between 0 and 1. How it changes relative to real-world time is controlled by the easing function, which you can read about here.

Back