I was making a game using D3.js to add SVG elements and I needed to make multiple SVG elements/shapes to rotate at their own center.
Before we get to the rotation part, let’s create some SVG shapes using D3.js:
Creating a board to hold my SVG elements:
var board = d3.select('body')
.append('svg')
.attr('height', 300)
.attr('width', 400)
.style('background-color', 'black')
Creating six ellipses:
var elli = board.selectAll('.elli')
.data(d3.range(6)) // creating six
.enter()
.append('ellipse') //creating ellipses
.attr('rx', 5) //height
.attr('ry', 14) //width
.attr('cx', function() { //place at random positions
return (Math.random() * 300);
})
.attr('cy', function() {
return (5 + Math.random() * 250);
})
.attr('fill', 'deepPink'); //make them pink
Now we should have something looks like this: six pink ellipses placed that random positions.
Let’s get them to rotate:
SVG has some very easy to use animations such as rotation, but however it rotates in in circles around a point that’s at the top left corner of the SVG canvas if you don’t specify the center to be the center of the SVG canvas.
I found a helpful article that teaches how to set the center of the rotation.
… but I did not get it to work on multiple SVG elements at the same time. After hours of research, I found GSAP:
It animates anything JavaScript can touch (CSS properties, canvas library objects, SVG, generic objects, whatever) and it solves lots of browser inconsistencies, all with blazing speed (up to 20x faster than jQuery).
to make them rotate:
function transformOriginRotation() {
tween.seek(0).kill(); //reset
tween = TweenLite.to(ell, 1, {
rotation: 360,
transformOrigin: "50% 50%" //set the center
});
tweenCode.innerHTML = 'TweenLite.to(".elli", 1, {rotation:360, transformOrigin:"50% 50%"});'
};
setInterval(transformOriginRotation, 600);
taaaaadaaaaa… there we have it! Rotating ellipses!! Please click on ‘edit on codepen’ to see the animation.