Force layout node rotation

1k views Asked by At

Ok, first - look at this fiddle. You should see shapes rotating back and forth like crazy.

This is what is going on:

force.on("tick", function(e) {
  vis.selectAll("path")
      .attr("transform", function(d) {
        return "translate(" + d.x + "," + d.y + ")"

              // this is the thing
              +"rotate(" + Math.random() * 50 + ")";
    });
});

On every tick I'm changing the transform: rotate() to Math.random() * 50 in this case.

Now what I want is a smooth rotation. Not this jerky stuff.

See this to better understand what I mean. Imagine the height as the rotation. The gray box represents what I have now, the blue - what I want.

I tried applying 'transition: all 1s ease' CSS to that element, but it just ignores it, I'm obviously doing it wrong. So how do I make this infinite back and forth rotation smooth as if I was using CSS3 transitions?

1

There are 1 answers

2
Ethan Jewett On BEST ANSWER

Every tick you are randomly setting the rotation to something between 0 and 50 degrees of rotation. You need to maintain the current rotation, calculate an offset, and then set the rotation to the current + offset.

Here's an updated tick function:

force.on("tick", function(e) {
  vis.selectAll("path")
      .attr("transform", function(d) {
        if(!d.rotate) { 
            d.rotate = Math.random() * 50;
        } else {
            d.rotate = d.rotate + 1;
        }
        return "translate(" + d.x + "," + d.y + ")"
              +"rotate(" + d.rotate + ")";
    });
});

Here's the updated working example: https://jsfiddle.net/1aLc7x4j/