jczaplew
jczaplew

Reputation: 1753

Changing CSS with d3.transition()

I am using D3 transitions to rotate text, but am running into a strange problem. When rotating from 0 to -90 degrees, the transition works as expected. However, when transitioning from -90 degrees to 0 the transition does not work. An example can be seen here - http://jsfiddle.net/t7MRa/. The code to transition to 0 degrees is:

d3.selectAll("h2")
   .transition().duration(1000)
   .style("-webkit-transform", "rotate(0deg)");

I have tried .style("-webkit-transform", "none") which did not work. Any tips on what I am doing wrong? Thanks!

Upvotes: 1

Views: 692

Answers (1)

Scott Cameron
Scott Cameron

Reputation: 5323

D3 uses getComputedStyle to determine the starting value for transitions. Unfortunately, getComputedStyle for CSS transforms returns the transform matrix, not the transform string you specified. So, the starting point for the reverse transition looks something like this:

matrix(0, -1, 1, 0, 0, 0)

(I'm not actually sure why the first transition works. The transform matrix value when there is no transform on the element is "matrix(1, 0, 0, 1, 0, 0)" and somehow the string interpolator is able to do something with that but I don't know why.)

To work around this, you have a few options:

  1. If your start and end points are well-defined (as they are in the example) you could create a custom tween that runs interpolateString yourself passing in the known start and end transforms based on the current state of the rotation as "rotate" strings.

  2. You could convert your "rotate" string to a transform matrix and pass that in to transition.style instead. The MDN article on CSS transform says that rotate(angle) is equivalent to [cos(angle) sin(angle) -sin(angle) cos(angle) 0 0].

  3. You could switch to using SVG with a text element. SVG transforms are well understood by d3 and will work in most cases (your examples being one) without special handling on your part.

I did find a bug report pertaining to Firefox where there is some discussion about changing this, but considering the same behavior appears in both Firefox and WebKit it seems like we'll be living with this behavior for a while.

Upvotes: 3

Related Questions