Simple Shapes
IE[a] | Firefox | Safari | Chrome | Opera | iPhone | Android |
|---|---|---|---|---|---|---|
7.0+ | 3.0+ | 3.0+ | 3.0+ | 10.0+ | 1.0+ | 1.0+ |
[a] Internet Explorer support requires the third-party explorercanvas library. | ||||||
Every canvas starts out blank. That’s boring! Let’s draw
something. You can use the onclick
handler to call a function that draws a rectangle (see http://diveintohtml5.org/canvas.html for an interactive
example):
function draw_b() {
var b_canvas = document.getElementById("b");
var b_context = b_canvas.getContext("2d");
b_context.fillRect(50, 25, 150, 100);
}The first line of the function is nothing special; it just finds the
<canvas> element in the
DOM. The second line is where it gets more interesting.
Every canvas has a drawing context, which is where all the fun stuff
happens. Once you’ve found a <canvas> element in the
DOM (by using document.getElementById() or any other method
you like), you can call its getContext() method. You
must pass the string "2d" to the getContext() method:
function draw_b() {
var b_canvas = document.getElementById("b");
var b_context = b_canvas.getContext("2d");
b_context.fillRect(50, 25, 150, 100);
}So, you have a <canvas> element, and you have its drawing context. The drawing context is where all the drawing methods ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access