A Tutorial for HTML 5 Canvas Animation
One of the more exciting syntactical features released with HTML5 is the "<canvas>" element. The <canvas> element creates a drawing surface. In many ways, it is the programmer's equivalent of the painter's canvas, providing a blank rectangle on a Web page that can be scaled to any size. JavaScript then operates like paint, allowing you to draw or animate anything on the canvas. The most challenging aspect of creating an HTML5 canvas animation is not understanding the <canvas> element itself, but knowing how to "paint" JavaScript animations on top of it.
Instructions
-
-
1
Open a new blank document and title it "canvas-animation.html." Opening your new document in a Web development application can make editing easier, but if you don't have one just use a basic text editing application.
-
2
Write the code to define your HTML5 document, including the doctype, head and body of the document. As in the following example, set the character set and the title in the document head:
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>HTML5 Canvas Animation</title>
</head>
<body>
</body>
</html>. -
-
3
Add <section> and <canvas> tags to the body of your document. The section tag is new in HTML5. It defines sections in a Web document. The canvas tag defines the rectangular canvas you will use to build your JavaScript animation. The following example has the ID "animation," which will be used as a reference by your JavaScript:
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>HTML5 Canvas Animation</title>
</head>
<body>
<section>
<canvas id="animation"></canvas>
</section>
</body>
</html>. -
4
Set the width and height of your canvas and fill it with text to be displayed on browsers that don't support HTML5. The canvas can be set to any size, depending on your needs. Remember, however, that larger canvases take longer to load. Here is an example:
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>HTML5 Canvas Animation</title>
</head>
<body>
<section>
<canvas id="animation" width="500" height="500">
Sorry, your browser doesn't not support HTML5 and, in turn, cannot load this animation.
</canvas>
</section>
</body>
</html>. -
5
"Paint" your JavaScript animation onto the <canvas> element using the "getElementById()" method to connect your scripts to the canvas' "animation" ID. If you don't have prior experience writing JavaScript animations, there are a number of examples you can try provided in the Resources section of this article.
-
1
Tips & Warnings
A basic understanding of JavaScript animation is necessary for building HTML5 canvas animations. If you don't have this, refer to the "Resources" section for examples.
References
Resources
- Photo Credit Dynamic Graphics Group/Dynamic Graphics Group/Getty Images