3D Animation in SVG


10 Sep 2011 Code on Github

I've been experimenting a bit further, with shading and a bit of animation. I decided to make a mobile after seeing the Google logo celebrating Alexander Calder's 113th Birthday, which I think was some sort of Canvas animation.

I should make it clear that I don't creating 3D animations with SVG is a particularly good idea, since SVG really isn't designed for three dimensions; I just wanted to see how far I could get. I'm still quite amazed that the above SVG is simply a few 2D paths drawn over and over again. The code I've written is not pretty and very hacky, but it works for this test case. I might be able to make things a bit easier by using matrix transformations, but I don't think it will help a great deal.

The hardest part was to get the SVG to display its elements in the correct order, e.g. so the triangle in front is drawn on top of the triangle behind. Because of the way SVG works, the only way to achieve this is to manipulate the DOM, as I described here. In fact, you need to clone an element, append it to the end of a node, and then delete the original.

function moveTriangleToBottom(n){	    
    var t1 = document.getElementById('triangle'+n);
    var t2 = t1.cloneNode(false);
    var parent = document.getElementById("triangles")

    parent.appendChild(t2);
    parent.removeChild(t1);
}

The edges are easier to deal with because only one is ever visible, so we can simple change the visibility of the other to 'hidden'.

Comments (4)

3d animation on 2 Mar 2012, 10:59 a.m.

Great job. I really appreciate your work. It is very helpfull. Keep it up.

Anonymous on 21 Oct 2013, 12:10 p.m.

Cool example to look as 3d animation in SVG. Thanks for your help

Ver Nick on 4 Dec 2018, 8:25 a.m.

Thanks.

Joemon on 9 Sep 2020, 7:48 p.m.

great!