HTML and CSS Reference
In-Depth Information
Multiple Balls Bouncing with a Dynamically Resized Canvas
Before we move on to more complex interaction among balls, let's try one more thing. Back
in
Chapter 3
, we resized the canvas with some HTML5 form controls to display text in the
center of the canvas. Well, let's do the same thing now with the ball example. This will give
you a better idea of how we can make objects interact with a dynamically resizing canvas.
First,intheHTML,wecreatetwoHTML5
range
controls,onefor
width
andonefor
height
,
and set their maximum values to
1000
. We will use these controls to set the width and height
of the canvas at runtime:
<form>
Canvas Width:
<input
<input type=
"range"
id=
"canvasWidth"
min=
"0"
max=
"1000"
step=
"1"
value=
"500"
//>
<br>
<br>
Canvas Height:
<input
<input type=
"range"
id=
"canvasHeight"
min=
"0"
max=
"1000"
step=
"1"
value=
"500"
//>
<br>
</form>
In
canvasApp()
,wecreate theeventlisteners fortheHTML5formcontrols.Welistenforthe
change
event, which means that any time the
range
control is moved, the event handlers will
be called:
formElement
=
document
.
getElementById
(
"canvasWidth"
)
formElement
.
addEventListener
(
'change'
,
canvasWidthChanged
,
false
false
);
formElement
=
document
.
getElementById
(
"canvasHeight"
)
formElement
.
addEventListener
(
'change'
,
canvasHeightChanged
,
false
false
);
The event handler functions capture the changes to the range, set
theCanvas.width
or
theCanvas.height
, and then call
drawScreen()
to render the new size. Without a call to
drawScreen()
here, the canvas will blink when the new size is applied in
drawScreen()
on
the next interval: