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, in the HTML, we create two HTML5 range controls, one for width and one for 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 type="range" id="canvasWidth"
       min="0"
       max="1000"
       step="1"
       value="500"/>
 <br>
 Canvas Height:  <input type="range" id="canvasHeight"
       min="0"
       max="1000"
       step="1"
       value="500"/>
 <br>

</form>

In canvasApp(), we create the event listeners for the HTML5 form controls. We listen for the 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);

formElement = document.getElementById("canvasHeight")
formElement.addEventListener('change', canvasHeightChanged, 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 ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.