Time for action – adding a text tool
Let's start by adding a new item to the Tool drop-down menu for the text tool:
<li data-value="text">Text</li>
Next, we'll add a drawText()
method to the Canvas2D
object. It will take the text to draw, a point from where to draw the text, and a Boolean value indicating whether to fill the text or just outline it. If fill
is true
, it uses fillText()
to draw the text, otherwise it uses strokeText()
:
this.drawText = function(text, point, fill) { if (fill) { context.fillText(text, point.x, point.y); } else { context.strokeText(text, point.x, point.y); } };
Now we need a way to allow the user to enter the text that he/she wants to draw. We will need a text input field that we will keep hidden until the user wants to add some text. When the user selects the text tool and clicks on the canvas, we will position the text field where he/she clicked on and wait for him/her to enter the text. When the user presses the...