Animated Gif on Canvas

Published date: Aug 19, 2009

The canvas tag allows you to reference an image element in the DOM and render it inside the canvas through the drawImage method. That image source can also be an Image object created with Javascript.

Instead of an image, we can use another existing canvas as the source of the drawImage method. The third square is a canvas that loads from another canvas (2nd square) which in turn loads from an image.

If we set a render interval to both canvas then anything that happens on the second one affects also the third one. The first canvas only takes care of the horizontal movement whereas the second one takes care of the vertical one. Both combined create the bouncing effect advancing to the right.

However, if we add an animated GIF as the first source, every time a drawImage call happens it will render whatever the status of the GIF is at that very second. This way, we can add an extra animation to the final results with the same steps (as if we were importing an animation). Likewise, we can get the same results as the previous sample with one less step. Again, the first canvas is taking care of the horizontal movement whereas the second one adds some random movement to it.

We can also create an image sprite through the cycle loading time of the GIF. However, it's kind of difficult to match the right timing pattern of the image animation.

Conclusions

There are no conclusions from all of this. Here I wanted to show you a feature of the canvas element that I didn't pay much attention until now. That is, the use of the drawImage method taking an animated GIF as a source instead of a static image. Whether this can be useful or not will depend on trying these techniques in your specific canvas experiment to see if they can really replace any current technique and maybe get the benefits of a simpler algorithm or better performance.

Browser Compatibility

This works fine on Firefox, Chrome and Safari. IE through excanvas implementation will insert the animated GIF in the canvas as it is (it will play constantly but it won't be possible to capture the partial statuses of the animation in the canvas). Surprisingly, Opera chokes on rendering the animated GIF showing only the first frame of it. Since the IE and Opera cases failed in the initial tests they are not supported in the samples of this page either.

Update: As Matthew @p01 (of Defender of the Favicon fame) points out, Opera is the only one that is actually following the spec: "When the drawImage() method is passed an animated image as its image argument, the user agent must use the poster frame of the animation, or, if there is no poster frame, the first frame of the animation."

Go Back To Main Page