Animating with canvas and creating CSS3 animations with JavaScript

Monday, September 5th, 2011 at 3:25 pm

Yesterday we went to a cool park in Krakow, Poland where they have all kind of physics experiments for kids (and me):

Physics Park exhibits

One of the things that always fascinated me was the optical illusion of non-concentric circles turning into a 3D cone. Take the following picture:

non-concentric circles

And then rotate it and you see what I mean (video on screenr).

Now, coming back (like any other kid) I wanted to recreate this for myself, and it is actually pretty easy in HTML5 canvas. If you get the embed below, then click the play button to see the result.

Check the source code. In essence all you do is paint a number of concentric circles with alternating black and white colouring and you decrease their radius. Instead of keeping the centre of the circles the same you move it back forth with a sine wave.

The animation works simply by rotating the canvas around the centre – no need to calculate the rotation in the loop.

This is what also ailed me about this: as the main image doesn’t change and we simply rotate the canvas, there is no need for the painting loop in the animation. Although the performance seems to be fine (at least here on this Macbook Air), I am pretty sure that the animation without the calculated circles will be smoother and less resource hungry. That’s why I painted the circles in one canvas and copy it into the animated one as an image. You can see the two canvases (the painting one in lighter grey) in this demo. Again, if you get the embed below, then click the play button to see the result.

The next step was to take the advice that everybody tells you right now and think about CSS animation as it is hardware accelerated and much better (citation needed, but that is the impression that I get). As all I am doing is to rotate a canvas around itself, it seems to be a good idea to do that. So, in the next example I animate with CSS and only use canvas for painting:

Smooth! I like it. What I don’t like is that now it does nothing in Opera for example. The other thing that annoys me is that the CSS is ridiculously verbose as I have to repeat all the animation information and keyframes for each browser with different prefixes.

That’s why I wanted to see if I can use CSS animation when it is supported and create the animation on the fly. That can be done but it is not that easy. Check out the result.

This seems to work nicely, try it in Opera and in other browsers to see the differences and get information what kind of animation was used. If I used transformation instead of animation it would even be easier. As it stands now, you can’t access, create and change keyframes that easily. this post has some more info on the issue and Joe Lambert did another showcase. Makes you wonder if we shouldn’t create an easier bridge between JS and CSS animations.

Tags: , , ,

Share on Twitter