To create an animation using HTML5 Canvas, we can use the requestAnimFrame shim which enables the browser to determine the optimal FPS for our animation. For each animation frame, we can update the elements on the canvas, clear the canvas, redraw the canvas, and then request another animation frame. 21 Ridiculously Impressive HTML5 Canvas Experiments. Let's take a peek at some of the latest, cutting edge examples out there. Particle Letter Animation. Cloth Experiment. This is one of the best canvas-based experiments. Particle System.
Introduction
HTML5 is becoming more and more popular. With the increasing popularity of mobile devices such as tablets and smartphones, the need for alternatives to the popular Flash plugin from Adobe has also been growing. Just recently, Adobe announced that Flash will no longer be supported for mobile devices. This means that Adobe itself will focus on HTML5 as a key technology for those devices - and desktop systems sooner or later.
One disadvantage of HTML was the lack of multimedia techniques. In HTML, you could not display a video or draw on the screen. With HTML5, new elements such as <video>
and <canvas>
have been introduced. Those elements give developers the possibility to use multimedia technology in 'native' HTML, just by writing some JavaScript in combination with HTML. A basic action that should be provided by multimedia technologies is animation. In HTML5, there are some ways to create such actions.
In this article, I will only compare the new <canvas>
element with the upcoming CSS3 animation technique. Other possibilities would include the creation and animation of DOM elements or SVG elements. Those possibilities will not be included in this discussion. It should be noted from the beginning that the canvas-technology is supported in the current releases of all major browsers, while CSS3 animations are only possible in the latest editions of Firefox and Chrome. The next IE will also provide CSS3 animations.
Background
I am currently giving a lecture on creating WebApplications using HTML5, CSS3 and JavaScript. This is a lecture with tutorials. For one of the tutorials, I picked a sample canvas animation - just showing in which direction we are heading to with a technology like this. Then I introduced the CSS3 animation in the lecture (everyone was very excited about it) and wanted to create a simple homework task using the CSS3 animations. What came to my mind was: How easy or hard would it be to actually transform the canvas animation into a complete CSS3 animation?
This involved several parts:
- Creating all the different
<div>
-elements in order to 'box' everything - Draw everything using styles on those elements with style rules like borders, background-gradients and rounded corners
- Actually animating the elements
The reason for using CSS3 animation over the <canvas>
-element is quite important: While browsers can optimize their elements performance (regarding their style, i.e. CSS), they cannot optimize our custom drawing routines used in a canvas. The reason for this lies in the browser's ability to use hardware mainly the graphics card. Currently the browser does not give us direct access to the graphics card, i.e., every drawing operation has to go over some function in the browser first.
This problem could be prevented with techniques such as webgl, where the browser does give the developer direct access to the graphics card. However, this is treated as a security problem and will not become standardized. One important rule for developing WebApplications is standardization - since this is our portal to a huge customer base. If we excluded some of the most popular browsers, we would certainly lose a lot of potential visitors.
Starting with Canvas
Our basic HTML document looks like the following:
Here we set the HTML5-Doctype and build a page containing a <canvas>
for drawing the animation and some buttons contained in a panel (<div>
). We could have shortened the document by omitting certain tags. One of the advantages of HTML5 is that each browser has to implement certain fallbacks, e.g., if a tag is not closed or if a certain tag is missing. The shown (more complete and verbose) form is my personal favorite.
A canvas alone would not make a great painting - nor does it give us some animation. What does the actual drawing? It's some JavaScript! The required <script>
-tag is already placed in the <head>
-section. In this case, we will not use external JavaScript files to get the required lines of code. This only makes sense if you consider using not many lines of code (small size) and non-repeating JavaScript. Otherwise, you could benefit from the browser's caching as well as multiple (download) connections. Another important point by using external JavaScript files is to consider moving the script-tags to the bottom of the document in order to prevent performance problems.
Let's start by declaring some variables:
As you can see, most of the variables are actually used as constants. This means the code will give you some freedom in order to adjust the dimensions of the car as well as some other parameters like the speed of the car. The change in the rotation of the tire can actually be calculated by using the ratio of dx
to the radius
.
Another interesting property arises by looking at the bottom of the code. Here I use an anonymous function. This can be very useful in some cases. This means that variables that are declared within the scope of the anonymous function like car
will be deleted by the browser and most importantly will not cause any conflicts with other existing variables.
Why is there a second (invisible) canvas set up? First of all, this will be useful in the transition to CSS3. However, this approach is also very useful in general. By using a canvas for each major object we are animating, we will be able to keep their states as they are, i.e. if we do not have to redraw them we do not have to as supposed to the approach where we will wipe does drawings away with a clean of the main canvas. Another reason is that this model allows us to think more physical. We do not have to animate the chassis (moving) and the tires (moving and rotating) separately, but just as a whole thing meaning the tires (rotating) within the car (moving). This projects the physical model more closely, where the tires are rotating which makes the car moving.
Starting the loop:
This function has already been referenced by the HTML we've written. Here we just start or stop the animation depending on the current state that is displayed using the ani
variable. The framerate has a maximum of 25 frames per second - this might not be the best choice. jQuery is using 77 fps (13 ms) as a default for its DOM object animation. In case of this simple animation, it should give a good insight. An important issue is that our logic (dx = 5
) will be bound to those 25 fps. This is something to be careful about when building professional animations or even games.
Let's have a look at the main drawing function that will be called in the loop:
Basically we just redraw the image. The animation is actually coming from two little methods inside. First we use a translation of coordinates to always draw to the same coordinates but being placed on a different location. The second one is the incrementation of the car's current position. Without one of those two calls, the car would not move at all! We also outsourced as much code as possible, making it more maintainable (unfortunately this can also decrease JavaScript code performance).
Why are coordinate transformations so important? They offer us some nice possibilities: Rotating something without writing any mathematical function at all! Or as we have seen: We can just draw to the same coordinates but receive different results. This is the power of coordinate transformation. The translation method is called by using context.translate(dx, dy)
and allows us to set a new center (0, 0). The usual center is the upper left corner. If we would rotate without translating at all, we would always just rotate around the upper left corner. In order to rotate around the center of a canvas, we could use something like:
Now we look at the function for drawing the car itself:
Here we used some of the possibilities that the <canvas>
-element offers us. On the hand we do use paths (very simple - and in this case more or less obsolete since we could have used the drawRect()
and fillRect()
method. Again we outsourced some code in order to obtain a better maintainability. In this case, this is totally justified since we just have one method to take care of (drawTire()
) instead of two identical code blocks that form one big mess.
Finally, let's have a look at the method for drawing one of the tires:
Additionally, I've added a preview image by using the onload
-event of the <body>
-element. I also included a method to increase the speed of the animation by changing the value of the dx
variable. The framerate will not be changed in order to increase or decrease the speed.
This example can be viewed live at http://html5.florian-rappl.de/ani-canvas.html.
Moving to CSS3
The basic HTML document now has the following format:
The document looks quite similar to the one before. However, some things can be noted right away:
- There is no
<script>
-element prepared. Instead, we will use a<style>
-declaration. - There are no controls for setting the speed or play and pause. This is actually one of the key differences I will explain later (interaction).
- The whole scene is already presented in HTML-elements. They are not styled right now, but they do represent the scenario we want to animate.
While animating something in a canvas is mostly a programming job, we clearly shifted towards a design problem here. We can only manage to animate the scene appropriately if we build a correct model of the scene using HTML-elements (well, <div>
s). In this logical scenario, the <div>
represents the canvas from before, <div>
is the HTML-element that is equivalent to the hidden canvas of the previous example and <div></div>
is exactly the element that has been drawn using drawGrass()
before.
The basic CSS outline is the following:
Here we use classes and IDs to attach rules one or multiple times. This can be seen best by looking at the code for creating a tire. We do use two different IDs (fronttire
and backtire
) for distinguishing between different positions. Since both share the rest of their properties (and a rotation!) it was just useful to give them also a class (tire
) which attaches some CSS rules to the corresponding elements.
The horizontal and vertical lines will be drawn using the classes hr
and vr
. We can use the position: absolute;
and position: relative;
rules to set positions for each child-element within the mother-element. For the grass, we required a gradient to be drawn. This is no problem in CSS3. Well, maybe it is a small problem since the browser vendors are currently using vendor specific prefixes for those rules. This is an annoying fact and will hopefully vanish within the next year.
A really important rule can be found in the container itself. By setting overflow: hidden;
we prevent the car from escaping from our beautiful container-world. This means that the car will behave the same way as in the previous scenario, where it was not possible to draw outside the canvas-area. However, one more really important thing is missing: the animations itself!
Definitions of the keyframes:
The first comment on those lines is a really important one: do not try making this at home! I do not show the real code here for a purpose. This is how it should look like. However, it does not (but it looks similar). The problem is that CSS3 keyframes are quite new and therefore (yes, you guess (or know) it) you require those prefixes again. Also CSS3 transforms do require prefixes. So just copy those lines and add -webkit-
and -moz-
and others (IE is about to come to the CSS3 animations party with version 10, hopefully Opera is about to follow!) in front of keyframes
and transform
.
The next thing you'll notice is that the syntax is really clean and smooth. You just specify some keyframes (in this case just one as an initial frame and one as a final frame) and the browser will calculate the rest. However, we cannot integrate such nice physical considerations like the relation between the angle and the position from the previous example.
Now that we specified some keyframes we need to integrate them! How does that look:
Again - be cautious when trying this at home. You will need some copy and paste plus you'll have to add the appropriate prefixes in front of those entries. So this tells the browser which set of keyframes to take for the element and what kind of frame distribution within which time to consider. We also tell the browser the number of repetitions to perform. In this case, we will end up with an infinite loop.
This example can be viewed live at http://html5.florian-rappl.de/ani-css3.html.
Another Approach: Hybrid!
Since the keyframes feature is not well supported, it is obvious that other possibilities have to be explored. One possibility is to combine the power of (available) CSS3 features such as linear gradient, transformations and transitions with the power of JavaScript. This means that we will have the best of both worlds. Even though some CSS3 features might be missing in one or the other browser, it could be possible to do quick replacements in the form of filters (possible in the Internet Explorer), images / scripts or even nested canvas elements.
The hybrid approach I am going to present right now will start off where the CSS3 keyframes example stopped. The only thing that has to be modified are all @keyframes
and animation
rules in the CSS stylesheet. Once these lines have been removed, we are stuck with a static image. Now we do see the environment, but nothing is happening. This is where JavaScript comes to help.
We could start with a loop as in the canvas example. However, I do want to present a different way. Since we are dealing with DOM objects, i.e. HTML elements like a <div>
, we could make use of the very effective (and cross-browser friendly) library jQuery. It is not only one of the fastest libraries - it is also one of the most popular ones. So we have to include a few new lines in the head of the HTML file. The <head>
element will be extended in the following way:
Here we use jQuery as a minified version from the Google CDN. The advantage of using popular libraries from public CDN of reliable hosts is that one might need fewer requests due to caching, has less traffic on the (own) server and serves the homepage faster since the client can make more requests in parallel (the number of requests to one host is limited from the browser). Now we will write some script using jQuery's ready
method. This method gives us the guarantee that the DOM has finished loading and is ready to be modified from our JavaScript.
So what are we doing here? First, I introduce two very useful variables. One will be used in order to determine the current status of the tires. It will save the current angle of the rotation. This angle will be incremented and used to set the rotation. The second one is a shame... Actually it is based on the statements I did make with the CSS3 keyframes. At the moment, browser vendors use their own prefixes for a lot of things - even though more and more rules are being standardized, this is required. My statements are a very easy approach to find out the actual statement that will be accepted by the browser as a CSS rule to set the rotation. Another (and more general) way would be to query the navigator
object which contains the browser name and more. That information could be used to set a global prefix like -o-
, -moz-
etc.
The next two objects are introduced to give some kind of extensibility to the code. Both will be used in order to determine starting point and end point of the animation. These objects can be extended or modified in order to produce a different animation based on the same basic environment. The rotate
function will be used in each frame and will perform the rotation on the tires using jQuery's built in css() modification function.
Now we do create the options object containing the duration, the step callback and the complete callback. The last one will be used to produce the infinite loop as in the CSS3 example. We actually do set the options variable that is just created as the options reference for the jQuery animate()
function. Before we call the animate()
method, we use jQuery's CSS method again. This will ensure that we animate from the starting point to the end point. Here we use jQuery's chaining to make to function calls (with the selector even three) in just one JavaScript statement.
The final step is to execute the animation using our complete callback. This hybrid approach does even work in IE 9 (except the linear gradient for the grass - I did not use a filter or other methods here to guarantee compatibility). It provides a cross-browser experience in Opera, Firefox, Safari and Chrome.
This example can be viewed live at http://html5.florian-rappl.de/ani-hybrid.html.
Bonus: How About Vector Graphics?
Yet there is another possibility that should be included in this list. This possibility is somehow out of the box, since it does not rely on HTML5 techniques like the <canvas>
element or CSS3 rules like rotations. However, this is the great advantage of this technique. On the one hand, it is compatible with older browsers and on the other sides it is possible to hardware accelerate it on newer browsers. I talk about the possibility to animate SVG graphics.
SVG is another standard that has been set by the W3C. It has been around for quite a long time and is a very successful file format for seamless vector graphic exchange. Popular programs like Inkscape heavily rely on the SVG format, which is based on XML. Many browser vendors do support including SVG graphics in websites. The advantages are obvious: The graphics scale nicely and do behave like real objects. This means that a hole in graphic does infact represent a hole (cannot be clicked), and not just a bunch of pixels in a different color. With SVG, it is possible to create complex objects which can really be treated like such.
One of the first browsers to support SVG was Opera. The support had only one major drawback: SVG could just be included externally, i.e., not in the same document (HTML), but in an external *.svg file. This drawback has just now (about 3 months ago) been removed. One possible workaround was to use VML in the HTML document. VML is another description language for vectors. It was the language of choice from the Internet Explorer team. Today IE 9 also supports SVG, but former versions of IE just supported VML. How do we get around this mess (VML, SVG, ...)? We pick a JavaScript library that gives us a better cross-browser experience. Something like jQuery for SVG... That one is named RaphaelJS!
How does the basic HTML code look like?
The HTML code looks a bit like one from the CSS3 keyframes or hybrid example, except we only make rules for the body and the container <div>
. The container will be used for our SVG animation. We note that we include jQuery again (to use jQuery's wonderful $(document).ready()
method. We also include the external JavaScript library raphael.js. This one has been downloaded from the website (raphaeljs.com/). The real work has now to be done - in JavaScript (again).
The code looks like a mixture of the hybrid approach with the canvas example. On the one side, we do have the same pattern; everything has to be initialized in JavaScript and not in CSS. We could write the SVG in HTML directly, however, this would take away the cross-browser advantage that Raphael is offering us. This cross-browser advantage is based on the fact that Raphael can create VML code as well - if that is the only one supported by the executing browser. Anyway: We want to stay on the save side and therefore we have to do everything in JavaScript. After initializing all the objects over the variables we introduced, we have to group them in a way and execute the animation.
As with jQuery, we have to set the callback method for finishing the animation to the animation itself. Therefore we create an infinite loop since the animation is recreated on ending. This also creates the requirement for a reset of the objects' properties. As we do see: The code as not as clean as with the hybrid approach and not as messy as with the canvas approach. After all, SVG should be your first choice if you need scalability. It would also be your first choice if you want rich mouse interaction without any hit detection happening.
This example can be viewed live at http://html5.florian-rappl.de/ani-svg.html.
Comparison of the Two Methods
In my opinion, both of those methods have their benefits. The first one is actually pretty straight forward from a programmer's perspective (however, it took quite long until this was possible in HTML / JavaScript). The second one does offer some really nice features and will most certainly be used in an amazing way to build websites that will certainly have an impact on the web's future.
Pro Canvas-Animations
- Interaction (like pause, slower, faster, ...) is easily possible.
- We can connect values to form one physical unit directly.
- We do not need to know or have a complete structure before the animation.
- We are completely free from the CSS prefix hell.
Pro CSS3-Animations
- The performance is definitely better.
- We can use the full screen (100% does not work with the canvas element).
- The frames are computed by the browser - we just specify the keyframes.
- We do not need JavaScript (could be switched off).
All in all, it will depend on the project (as usual). Even though I thought about some possible workarounds to actually stop an infinite CSS3-animation (and start again), it would be tedious to actually implement this in a bigger multimedia animation. Here, the interaction possibilities are a clear indicator for a canvas-animation. On the other side, some small (non-interactive) animations could be done by the CSS3 technique. It provides a nice clear syntax that can be GPU accelerated by modern browsers and can be styled to fit everywhere.
Update: Pro Hybrid-Approaches
- The performance is better than on canvas.
- We can use the full screen (100% does not work with the canvas element).
- The frames are computed by us (or jQuery in this case).
- We can provide rich interactions with JavaScript and can still show the basic image without JavaScript.
I really do like the hybrid approach since it gives a lot of flexibility with a lot of comfort. It is one way to work around the CSS3 prefix hell that is going on right now - however, this argument just applies to certain situations and might totally crash in others. Another possible hybrid approach would be to build the separate parts with separate <canvas>
elements and perform JavaScript (with or without jQuery) or even keyframe animations on them.
Update: Pro SVG-Animations
Html5 Canvas Animation Library
- The performance is better than on canvas.
- Rich mouse interaction with the elements is possible.
- The elements are scaling very nicely.
- It is the approach that most browsers will understand.
I like SVG, but that goes hand in hand with RaphaelJS. I tried to write SVG code by hand - several times. Every element has special attributes, every attribute has its own syntax and there are so many elements. Also you have to consider special namespaces and so on. There is a lot of mess going on and this makes a good library necessary. Since there might be some problems with some browsers a good approach contains VML code as well. Next you want to have the power of chaining (or better: the same approach as in jQuery) plus animations (also jQuery like) and lots of other features. This is all offered by RaphaelJS. I would just make one statement to SVG: I Don't Always Use SVG, but when I do I Use RaphaelJS.
Points of Interest
While writing a lot of <canvas>
-animations, I never had the opportunity to write an actual CSS3 animation. This was certainly related to the propagation of this really new technique. Now that Firefox implemented the keyframes and with Microsoft up to come we will most certainly see more keyframe rules online. I thought that this technique was quite hard to write and got really surprised how easy it is. I actually had more problems with the linear gradient syntax than the keyframes one.
My only hope is that browser vendors will stop rolling out CSS rules with those prefixes. In nightly builds or such they are acceptable, but having something in a final build that is either not the standard (why rolling it out?) or standardized (why prefixing it?) but with a prefix is just a mess for web developers.
History
- v1.0.0 | Initial Release | 09.12.2011
- v1.1.0 | Update (Some typos fixed, included hybrid approach) | 11.01.2012
- v1.2.0 | Update (Included SVG approach) | 22.01.2012
Html5 Canvas Animation Example Download Youtube Download
- HTML5 Tutorial
- HTML5 Demo
- HTML5 Tools
- HTML5 Useful References
- HTML5 Tag Reference
- HTML5 Resources
- Selected Reading
Canvas
HTML5 element <canvas> gives you an easy and powerful way to draw graphics using JavaScript. It can be used to draw graphs, make photo compositions or do simple (and not so simple) animations.
Example
Html5 Canvas Demo
Below example works based HTML5 Canvas and JavaScript.
You can download demo from here.
Html Canvas Animation
HTML5 Canvas Demo Game
Below example works based HTML5 Canvas and JavaScript.
Html5 Canvas Animation Examples
You can download demo from here.