O'Reilly logo

HTML5 Web Application Development By Example Beginner's guide by J.M. Gustafson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required