HTML and CSS Reference
In-Depth Information
Let's add some graphics to our “Hello World!” text. First, let's load in an image and display
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
Before you display it, you need to wait for the image to load. Create an anonymous callback
function for the
Image load
event by setting the
onload
function of the
Image
object. The
anonymous callback function will be executed when the
onload
event occurs. When the im-
agehasloaded,youthencall
context.drawImage()
,passingthreeparameterstoputitonthe
canvas:
Image
object,
x
position, and
y
position:
var
var
helloWorldImage
=
new
new
Image
();
helloWorldImage
.
onload
=
function
function
() {
context
.
drawImage
(
helloWorldImage
,
160
,
130
);
}
helloWorldImage
.
src
=
"helloworld.gif"
;
Finally, let's draw a box around the text and the image. To draw a box with no fill, use the
context.strokeStyle
property 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
forthe
strokeRect()
methodaretheupperleft
x
and
y
coordinates,thewidth,andtheheight:
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
<html lang=
"en"
>
<head>
<head>
<meta
<meta charset=
"UTF-8"
>
<title>
<title>
CH1EX3: Your First Canvas Application
</title>
</title>
<
script src
=
"modernizr.js"
><
/script>
<
script type
=
"text/javascript"
>
window
.
addEventListener
(
"load"
,
eventWindowLoaded
,
false
false
);