Let's add a tool to draw rectangles. We'll start by adding a menu item to the Tool drop-down menu with its data-value
attribute set to "rect"
:
<li data-value="rect">Rectangle</li>
Let's implement the drawRect()
method in Canvas2D
:
this.drawRect = function(point1, point2, fill) { var w = point2.x - point1.x, h = point2.y - point1.y; if (fill) context.fillRect(point1.x, point1.y, w, h); else context.strokeRect(point1.x, point1.y, w, h); return this; };
Our drawRect()
method takes three parameters; the two points that define top-left and bottom-right coordinates, and a Boolean value to determine if the rectangle should be filled. Since fillRect()
and strokeRect()
both take width and height parameters we need to compute them by subtracting the point1
variable's coordinates from point2
variable's coordinates.
Before we code up the call to drawRect()
there is one piece of business we need to take care of. Our drawRect...