HTML and CSS Reference
In-Depth Information
Finally, we use the
setAttribute()
method to set the “style”:
function canvasStyleSizeChanged(e) {
var styleWidth = document.getElementById("canvasStyleWidth");
var styleHeight = document.getElementById("canvasStyleHeight");
var styleValue = "width:" + styleWidth.value + "px; height:" +
styleHeight.value +"px;";
theCanvas.setAttribute("style", styleValue );
drawScreen();
}
While trying to change
theCanvas.width
and
theCanvas.height
attrib-
utes, you might notice some oddities if you try to change the scale with
CSS at the same time. It appears that once you change the scale with
CSS, the
width
and
height
attributes update the canvas in relation to
that scale, which might not be the effect you are expecting. Experiment
with Text Arranger 3.0 to see how these different styles and attributes
interact.
The toDataURL() Method of the Canvas Object
As we briefly explained in
Chapter 1
, the
Canvas
object also contains a method named
toDataURL()
, which returns a string representing the canvas' image data. A call with no
arguments will return a string of image data of MIME type
image/png
. If you supply
the
image/jpg
as an argument, you can also supply a second argument between the
numbers 0.0 and 1.0 that represents the quality/compression level of the image.
We are going to use
toDataURL()
to output the image data of the canvas into a
<textarea>
on our form, and then open a window to display the actual image. This is
just a simple way to show that the function is working.
The first thing we do is create our last two form controls in HTML for Text Arranger.
We start by creating a button with the id of
createImageData
that, when pressed, will
create the image data with a call to an event handler named
createImageDataPressed()
.
We also create a
<textarea>
named
imageDataDisplay
that will hold the text data of the
image after the
createImageData
button is pressed:
<input type="button" id="createImageData" value="Create Image Data">
<br>
<br>
<textarea id="imageDataDisplay" rows=10 cols=30></textarea>
Next, we set up the event listener for the
createImageData
button:
formElement = document.getElementById("createImageData");
formElement.addEventListener('click', createImageDataPressed, false);
Then, in the
createImageDataPressed()
event handler, we call the
toDataURL()
method
of the
Canvas
object (
theCanvas
), and set the value of the i
mageDataDisplay
<textarea>