HTML and CSS Reference
In-Depth Information
We also need to change the way we draw the background for the application in the
drawScreen()
function so it supports a resized canvas. We do this by using the
width
and
height
attributes of
theCanvas
to create our background and bounding box:
context.fillStyle = '#ffffaa';
context.fillRect(0, 0, theCanvas.width, theCanvas.height);
//Box
context.strokeStyle = '#000000';
context.strokeRect(5, 5, theCanvas.width−10, theCanvas.height−10);
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;";