The Essential Guide to HTML5

(Greg DeLong) #1

CHAPTER 3


Let's take a break now. Its your turn, dear reader, to do some work. Consider the following HTML
document:




The Origami Frog





Your browser doesn't support the HTML5 element canvas.



Find your own image file and use its name in place of frogface.gif. Change the title to something
appropriate. Experiment with the line


ctx.drawImage(img,10,20,100,100);


That is, change the 10, 20 to reposition the image, and change the 100,100 to change the width and the
height. Make the changes and see if the program responds as you intended. Remember that as you
specify the width and height, you could be changing the shape—the aspect ratio—of the picture.


Now try another exercise: drawing two images on the canvas. Youll need to have two different variables in
place of img. For this task, give the variables distinctive names. If you are emulating Dr. Seuss, you can
use thing1 and thing2; otherwise, choose something meaningful to you!


Now, on to more drawing!


Lets see how to use gradients for this version of the program. You can use gradients to set the
fillStyle property. I didn't want to have the ball on top of a filled in rectangle, so I needed to figure out
how to draw the four walls separately.


A gradient is a type of object in HTML5. There are linear gradients and radial gradients. In this application
we use a linear gradient. The code defines a variable to be a gradient object, using a method of a canvas
context that we defined earlier with the variable ctx. The code for the gradient looks like this:


var grad;
grad=ctx.createLinearGradient(boxx,boxy,boxx+boxwidth,boxy+boxheight);


The gradient stretches out over a rectangle shape.

Free download pdf