HTML and CSS Reference
In-Depth Information
n Note There is no built-in way to wrap a long line of text into multiple lines of text. You have to write your own
code to segment the text according to your needs.
Drawing Images
Drawing on the HTML5 canvas is not limited to lines, curves, shapes, and text. You can also draw existing
image files on a canvas. This is particularly helpful when you wish to integrate an image that is more
complicated than a simple shape. Consider, for example, if you want to display a company logo on a
canvas. Re-creating the logo from scratch may not be the best option. Additionally, the logo may be too
complex to be drawn using the available canvas API. It would be much easy to load an existing logo image
and then render it on the canvas. Luckily, the drawing context offers the drawImage() method, which allows
you to draw images on a canvas.
Listing 4-11 shows the simplest form of using drawImage() .
Listing 4-11. Using the drawImage() Method in Its Simplest Form
var canvas = $("#MyCanvas").get(0);
var context = canvas.getContext("2d");
var img = new Image();
$(img).load(function () {
context.drawImage(img, 10, 20);
img.src = "images/html5.png";
This code creates an image on the fly using JavaScript code. Notice that the jQuery code also wires an
event handler for the load event of the image object. The load event is raised when an image is fully
loaded. Unless an image is fully loaded, you can't draw it on a canvas. Therefore, you call the drawImage()
method inside the load event handler. drawImage() accepts the image object to be drawn and x and y
coordinates where the image is to be drawn. The code then sets the image's src property to an existing
image file ( images/html5.png ). If you run the code in Listing 4-11, you see an image drawn on the canvas as
shown in Figure 4-14.
At times you may need to resize an image while drawing it on the canvas. For example, the original
image size may be larger than the canvas size, and you may wish to fit the image as per the canvas
dimensions. To accomplish this, you can use a variation of the drawImage() method that accepts the width
and height to which the image must be resized. Listing 4-12 shows how this is done.
Listing 4-12. Drawing an Image with a Specific Width and Height
var canvas = $("#MyCanvas").get(0);
var context = canvas.getContext("2d");
var img = new Image();
$(img).load(function () {
context.drawImage(img,0,0, canvas.width,canvas.height);
img.src = "images/html5.png";
As you can see, in addition to x and y coordinates, the drawImage() method also specifies the image's
width and height. In Listing 4-12, the image width and height are set equal to the canvas width and height.
Search WWH ::

Custom Search