HTML and CSS Reference
In-Depth Information
While it is very helpful to understand the nuts and bolts of working with
the canvas API, which this chapter will help expose you to, most prac-
tical projects use libraries that automate the usage of canvas for various
tasks. As you will see, some of the tasks can be quite tedious, so using
a helper library can be the key to keeping you productive and sane.
9.1 Drawing on a <canvas>
Problem
You want to draw graphic elements on your page rather than including them in as an
external image with the img element.
Solution
Use the canvas element in your markup:
<canvas id="mycanvas"></canvas>
The canvas element can have “fallback” content inside the tag, which
the browser will render only if canvas itself is not supported. While not
a strong feature for accessibility purposes, this does provide a modest
mechanism for alternate content that screen readers can make available
to the user. (For more on accessibility, see Chapter 7 .) Another approach
would be to insert the canvas element inside figure element and provide
alternative text through the figcaption (See Recipe 1.15 ). For more
information on providing fallback content for canvas, see http://www
.w3.org/TR/2dcontext/#focus-management .
Alternatively, you can create a canvas element dynamically, append it to the page, and
then use CSS to position it where you need it:
var mycanvas = document.createElement("canvas");
mycanvas.id = "mycanvas";
document.body.appendChild(mycanvas);
To draw into the canvas element, first get a reference to the canvas element's context
and then issue drawing commands against that reference:
var mycanvas = document.getElementById("mycanvas");
var mycontext = mycanvas. getContext ("2d");
mycontext.beginPath();
mycontext. moveTo (10, 10);
mycontext. lineTo (35, 35); // draw a line path from (10,10) to (35,35)
mycontext.strokeStyle = "#000";
mycontext. stroke (); // draw the line
 
Search WWH ::




Custom Search