1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
|
HTML 5 isn't just about making semantic sense out of the web, it's also been written with an eye toward making the web a more interesting place. One of the central parts of that interestingness is a new tag called the Canvas tag.
Canvas is quite simply a blank spot for you to draw. The best way to understand how canvas works is to simply dive in and see it in action. That of course raises an inevitable question, how many of you are going to see the following examples?
Well, here's the browser breakdown as of August 2009: Safari 3, Safari 4, FF 3.0, FF3.5 Opera 10, Chrome 3 and IE 7 & 8 (note that the IE support requires the third-party JavaScript Library, [http://code.google.com/p/explorercanvas/ explorer canvas], download it, add the script to your pages and IE 7 and 8 will play nice with Canvas).
== The blank slate of HTML 5 ==
Okay, so, what is the canvas tag? Well, here's the simplest case:
<pre>
<code><canvas></canvas></code>
</pre>
Like any other tag, canvas will show up in the page's DOM and can be accessed just like any other HTML element. And that's one of the main purposes of canvas, to provide a blank slate of HTML which you can then draw on and manipulate using JavaScript.
To get a better idea of what that means, let's create a slightly more complex example. Here's another blank canvas:
<pre>
<code><canvas id="mycanvas" width="600" height="300" ></canvas></code>
</pre>
If you're using one of the browsers above, here's what that code will look like rendered in the browser (note we've added a 1 pixel black border):
<canvas id="mycanvas" width="600" height="300" style="border: #000 1px solid;"></canvas>
Now let's access that blank slate and do something to it. To do that we'll select the element with some JavaScript and then use some drawing methods.
<pre>
<code>
var canvas = document.getElementById("mycanvas");
var canvas_context = canvas.getContext("2d");
canvas_context.fillRect(100,100,200,100);
</code>
</pre>
What we've done here is use the standard JavaScript <code>getElementById</code> function to select our canvas element. Then we need to call the getContext() method and set it to 2d. That's the required first step for using any canvas element. Now we know what you're thinking, is there a 3d context? Well, for now, the answer is no. But expect one to come along eventually, it's on the W3C's list of future features.
Once we've set the getContext() of our canvas we can then start drawing. In this case we're simply drawing a black rectangle 100 pixels from the top and 100 pixels from the left of our canvas' edge. The basic parameters of the fillRect method look like this: <code>fillRect(x, y, width, height)</code>. Other basic drawing methods like <code>fillStyle</code>, <code>strokeStyle</code>, gradient tools and more. You can get a full rundown on all the drawing methods in the [http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html WHATWG's current working draft].
Now for a live example, let's take the code above and wrap it in function and then call it from a link's onclick() handler.
<canvas id="mycanvas2" width="600" height="300" style="border: #000 1px solid;"></canvas>
<script>
function draw_mycanvas() {
var canvas = document.getElementById("mycanvas2");
var canvas_context = canvas.getContext("2d");
canvas_context.fillRect(100,100,200,100);
}
</script>
<a href="#" onclick="draw_mycanvas();return false">Click here to draw in Canvas element above</a>
The code for the above example looks like this:
<pre>
<code>
<canvas id="mycanvas2" width="600" height="300" style="border: #000 1px solid;"></canvas>
<script>
function draw_mycanvas() {
var canvas = document.getElementById("mycanvas2");
var canvas_context = canvas.getContext("2d");
canvas_context.fillRect(100,100,200,100);
}
</script>
<a href="#" onclick="draw_mycanvas();return false">Click here to draw in Canvas element above</a>
</code>
</pre>
Note that you can have as many canvas elements in a page as you'd like and each one maintains its own state, that is, drawing in one won't effect any of the others. To effectively target each one, just make sure it has a unique ID, or use hierarchical selectors.
== Doing more with Canvas ==
Okay so it can draw black boxes, who cares? Well, actually Canvas can draw a lot more that just black boxes. In fact, if you dig into the drawing methods available via the Canvas API and start writing some more sophisticated code, just about anything is possible.
The idea behind Canvas is to offer a way to create live graphs and charts that would previously have required a static image. Now it's true there are some JavaScript libraries that can create impressive charts and graphs without Canvas, but the Canvas tag can do all that and opens the door to much, much more.
Take images for example. Ever wanted to load an image into a page and then start messing with it using JavaScript? Let's see how easy that is using Canvas.
<pre>
<code>
function draw() {
var c = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.onload = function(){
c.drawImage(img,0,0);
// additional manipulations here
}
img.src = 'images/myimage.png';
}
</code>
</pre>
Or we can simply grab an image from the current page by selecting it via <code>getElementById</code> or similar method:
<pre>
<code>
window.onload = function() {
var c = document.getElementById("canvas").getContext("2d");
var img = document.getElementById("myimage");
c.drawImage(img, 0, 0);
};
</code>
</pre>
Once we have an image in our canvas element it's possible to do just about anything with it -- rotating, flipping, scaling, cropping and more.
Common use cases for dropping an image inside a canvas tag include adding icons or backgrounds to charts (which saves considerable load time compared to drawing everything from scratch). And of course yes, it's potentially possible to build a full blown browser-native version of the Gimp.
Remember kids, if it can be written in JavaScript, eventually it will.
For some more examples of how you can push the boundaries with the canvas tag, be sure to check out Mozilla's [https://developer.mozilla.org/Special:Tags?tag=Canvas_examples&language=en collection of Canvas experiments]. Also be sure to try out [http://htmlfive.appspot.com/static/tracker1.html this motion tracking system] which combines canvas and the HTML5 video tag to create real-time motion tracking in video.
== Conclusion ==
We've really only scratched the surface of Canvas in this intro, but hopefully it's piqued your curiosity about one of the few elements in HTML 5 that enjoys pretty darn good cross-browser support (IE 6 is about they only common browser that can't handle canvas).
If you'd like to learn more have a look at the WHATWG's [http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html draft spec of canvas] and be sure to check out Mark Pilgrim's Dive into HTML 5 which has a few [http://diveintohtml5.org/canvas.html more details on Canvas]. The Mozilla developer website has a [https://developer.mozilla.org/en/Canvas_tutorial nice, thorough look at the canvas element] and covers a few things we've skipped like image compositing and simple animations. The Opera dev crew also has a very nice tutorial that walks you through the process of building an in-browser [http://dev.opera.com/articles/view/html5-canvas-painting/ MSPaint-style app using canvas].
|