In this post, I’m going to begin an examination of one of the hottest new features of HTML5, namely the Canvas element.
What is Canvas, anyway?
The best place to start is at the beginning, and that’s with an explanation of what Canvas actually is. Canvas is a new element that is part of the HTML5 specification, and can be added to your markup as simply as this:
1: <canvas id="myCanvas" width="500" height="500"></canvas>
OK, we’re done. Let’s go home.
Of course, it’s not that easy. By adding the canvas element to the markup, if we browse the page containing the element in a modern browser that supports canvas (you can find out which browsers support canvas using caniuse.com), you’ll see a great big nothing. Why? Because all that the
Building a Template
To make life easier as we explore the HTML5 Canvas, I’m going to start with a basic set of markup and script, and in future posts in this series, I’ll add to that basic template. Since this will consist solely of HTML markup, CSS, and Javascript, you can use any text editor you like to follow along. I’ll be working with the Microsoft WebMatrix 2 beta, which you can download here (you can choose either the current v1 release, or the v2 beta, using the big green buttons in the upper right).
Here’s the basic template I’m going to use:
1: <!DOCTYPE html>
2:
3: <html lang="en">
4: <head>
5: <meta charset="utf-8" />
6: <title>HTML5 Canvas Template</title>
7: <style>
8: /* styles here */
9: </style>
10: </head>
11: <body>
12: <canvas id="myCanvas" width="500" height="500">
13: <p>Canvas not supported.</p>
14: </canvas>
15:
16: <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js" type="text/javascript"></script>
17: <script type="text/javascript">
18: $(document).ready(function() {
19: var canvas = $("#myCanvas").get(0);
20: var context = canvas.getContext("2d");
21:
22: function renderContent()
23: {
24: // we'll do our drawing here...
25: }
26:
27: renderContent();
28: });
29: </script>
30: </body>
31: </html>
Some things to note:
- On line 7, I’m setting up a