HTML and CSS Reference
In-Depth Information
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
attrib-
utes of the CSS style. For example, to scale the canvas to a 400×400 area, you might use this
CSS style:
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
<input type=
"range"
id=
"canvasStyleWidth"
min=
"0"
max=
"1000"
step=
"1"
value=
"500"
//>
<br>
Canvas Style Height:
<input
<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
false
);
formElement
=
document
.
getElementById
(
"canvasStyleHeight"
);
formElement
.
addEventListener
(
"change"
,
canvasStyleSizeChanged
,
false
false
);
Intheeventhandler,weusethe
document.getElementById()
methodtogetthevaluesfrom
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()
method to set the “style”: