Time for action – adding a rectangle tool

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 ...

Get HTML5 Web Application Development By Example Beginner's guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.