Dynamically Scaling the Canvas

Besides resizing the canvas using theCanvas.width and theCanvas.height attributes, you can also use CSS styles to change its scale. Unlike resizing, scaling takes the current canvas bitmapped area and resamples it to fit into the size specified by the width and height attributes of the CSS style. For example, to scale the canvas to a 400×400 area, you might use this CSS style:

style = "width: 400px; height:400px"

To update the style.width and style.height properties of the canvas in Text Arranger, we first create two more range controls in the HTML page:

Canvas Style Width:  <input type="range" id="canvasStyleWidth"
       min="0"
       max="1000"
       step="1"
       value="500"/>
 <br>

  Canvas Style Height:
  <input type="range" id="canvasStyleHeight"
       min="0"
       max="1000"
       step="1"
       value="300"/>
  <br>

Next, we set the event handler for each range control. However, this time we are using the same handler—canvasStyleSizeChanged()—for both:

formElement = document.getElementById("canvasStyleWidth");
formElement.addEventListener("change", canvasStyleSizeChanged, false);
formElement = document.getElementById("canvasStyleHeight");
formElement.addEventListener("change", canvasStyleSizeChanged, false);

In the event handler, we use the document.getElementById() method to get the values from both range controls. We then create a string that represents the style we want to set for the canvas:

"width:" + styleWidth.value + "px; height:" + styleHeight.value +"px;";

Finally, we use the setAttribute()

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.