460 CHAPTER 12 Drawing with HTML5
Lesson 1: Drawing by using the
The only significant attributes that the <canvas> element has are the height and width attri-
butes. The content that you place in the <canvas> element is displayed if the browser doesn’t
support the canvas element. The following is an example of a simple implementation of this
element, informing the user that a browser that supports HTML5 is required. This content is
displayed only if the browser doesn’t support the <canvas> element.
<canvas id="myCanvas" width="800" height="600">
You need a browser that supports HTML5!
</canvas>
For the subsequent examples, the following style is applied to the <canvas> element
because it is invisible by default.
canvas {
border: 1px solid black;
}
After this lesson, you will be able to:
■■Describe the <canvas> element.
■■Configure the drawing state.
■■Draw with paths.
■■Draw text and images.
Estimated lesson time: 20 minutes
The
The <canvas> element exposes an abundance of functionality through its canvas context,
which is accessible using JavaScript. This element provides the following members.
■■height Property that sets or gets the height of the canvas
■■width Property that sets or gets the width of the canvas
■■getContext() Method that accepts a parameter of 2d and returns a
CanvasRenderingContext2D object that represents the canvas context
■■toDataUrl() Method that creates a URL that can be used with an element that
requires an image URL, such as the <img> element
CanvasRenderingContext2D context object reference
The <canvas> element is simply a graphics container; the context object that is returned from
the getContext method is used to draw on the canvas. The following is a list of the context
object’s members. Many of these methods and properties are used in this lesson.