HTML5 Canvas [30]
In the drawScreen() function, we test the fillOrStroke variable to see whether it contains the value fill. Since we have three states (fill, stroke, or both), we use a switch statement to handle the choices. If the choice is both, we set the strokeStyle to black (#000000) as the highlight for the colored fillText.
If we use the xPosition and yPosition calculated using the width and height of the canvas, the message variable that contains the default or user-input text, and the fillOrStroke variable to determine how to render the text, we can display the text as configured by the user in drawScreen():
var metrics = context.measureText(message);
var textWidth = metrics.width;
var xPosition = (theCanvas.width/2) - (textWidth/2);
var yPosition = (theCanvas.height/2);
switch(fillOrStroke) {
case "fill":
context.fillStyle = "#FF0000";
context.fillText (message, xPosition,yPosition);
break;
case "stroke":
context.strokeStyle = "#FF0000";
context.strokeText (message, xPosition,yPosition);
break;
case "both":
context.fillStyle = "#FF0000";
context.fillText (message, xPosition,yPosition);
context.strokeStyle = "#000000";
context.strokeText (message, xPosition,yPosition);
break;
}
Example 3-1 shows the full code for Text Arranger. Test it out to see how the user controls in HTML affect the canvas. There are not many ways to change the text here, but you can see the difference between fillText and strokeText. In the next section, we will update this application to configure and render the text in multiple ways.
Example 3-1. Text Arranger 1.0