HTML and CSS Reference
In-Depth Information
Finally, we print our test on the screen by calling the fillText() method of the
context object. The three parameters of this method are text string, x position, and y
position:
context.fillText ("Hello World!", 195, 80);
Let's add some graphics to our “Hello World!” text. First, let's load in an image and
display it. We will dive into images and image manipulation in Chapter 4 , but for now,
let's just get an image on the screen. To display an image on the canvas, you need to
create an instance of the Image() object, and set the Image.src property to the name of
the image to load.
You can also use another canvas or a video as the image to display. We
will discuss these topics in Chapters 4 and 6 .
Before you display it, you need to wait for the image to load. Create a callback()
function for the Image load event by setting the onload function of the Image object.
callback() will be executed when the onload event occurs. When the image has loaded,
you then call context.drawImage() , passing three parameters to put it on the canvas:
Image object, x position, and y position:
var helloWorldImage = new Image();
helloWorldImage.src = "helloworld.gif";
helloWorldImage.onload = function () {
context.drawImage(helloWorldImage, 160, 130);
}
Finally, let's draw a box around the text and the image. To draw a box with no fill, use
the context.StrokeStyle() method to set a color for the stroke (the border of the box),
and then call the context.strokeRect() method to draw the rectangle border. The four
parameters for the strokeRect() method are the upper left x and y coordinates, and the
lower right x and y coordinates:
context.strokeStyle = "#000000";
context.strokeRect(5, 5, 490, 290);
The full code for the HTML5 Hello World! application is shown in Example 1-3 , and
its results are illustrated in Figure 1-3 .
Example 1-3. HTML5 Canvas Hello World!
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH1EX3: Your First Canvas Application </title>
<script src="modernizr-1.6.min.js"></script>
<script type="text/javascript">
window.addEventListener("load", eventWindowLoaded, false);
Search WWH ::




Custom Search