Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

490 CHAPTER 12 Drawing with HTML5


FIGURE 12-19 Changing the textAlign and the textBaseline to center the text within the canvas

Drawing with images


In addition to drawing the many shapes this lesson has covered, you might want to place
images on the canvas. You can do this by drawing the image on the canvas, using the
drawImage method of the context object.
The drawImage method can accept either three or five arguments. The first argument is
the source of the image, which can be an <img> or <video> element or another < canvas>
element. When the <video> element is used, a snapshot of the frame that is currently
displayed is used as the image. When passing three arguments to the drawImage method,
the second and third arguments are the x and y coordinates of the upper-left corner of the
image. You can also create the <img> element in your JavaScript, which is great for when the
presentation of the image might be conditional and you don’t want to waste time loading
the image unless it’s required. The following code example demonstrates the creation of the
<img> element dynamically, loading it with a photo of an iceboat. When the image is loaded,
the drawImage method is called, and the image is passed in as the first argument.
function drawImage() {
var canvas = document.getElementById('myCanvas')
, ctx = canvas.getContext('2d');
Free download pdf