Online Book Reader

Home Category

HTML5 Canvas [8]

By Root 6413 0
objects, or anything else. This is an example of the immediate mode we described earlier.

Again, we will discuss the text functions of Canvas in the next chapter, but here is a short preview of the code we will use to put the text “Hello World!” on the screen.

First, we set the color of the text in the same way we set the color of the rectangle:

context.fillStyle = "#000000";

Then we set the font size and weight:

context.font = "20px _sans";

Next, we set the vertical alignment of the font:

context.textBaseline = "top";

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.

NOTE

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!

CH1EX3: Your First Canvas Application

Your browser does not support HTML5 Canvas.

Figure 1-3. HTML5 Canvas Hello World!

Debugging with Console.log

There is one more thing to discuss before we explore bigger and better things beyond “Hello World!” In this book, we have implemented

Return Main Page Previous Page Next Page

®Online Book Reader