Time for action – adding a circle tool

Let's add a circle menu item to our Tool menu:

<li data-value="circle">Circle</li>

Now let's go ahead and add a drawCircle() method to Canvas2D. Our method will take the center point, the radius, and a Boolean value to determine if the circle should be filled:

this.drawCircle = function(center, radius, fill)
{
    context.beginPath();
    context.arc(center.x, center.y, radius, 0, 2 * Math.PI, true)
    if (fill) context.fill();
    else context.stroke();
    return this;
};

If the fill parameter is set to true we call context.fill() after calling arc(). Otherwise we just use context.stroke() to draw the outline.

Finally let's add the code to redraw() to draw the circle. Here we need to do a little work to find the radius to pass into drawCircle(). First we find the difference in x between the first and second point, then the difference in y. Whichever one is smaller we will use that as our radius:

switch (action.tool)
{
    // code not shown...
    case "circle":
        var dx = Math.abs(action.points[1].x – 
            action.points[0].x);
        var dy = Math.abs(action.points[1].y – 
            action.points[0].y);
        var radius = Math.min(dx, dy);
        canvas2d.drawRect(action.points[0], radius, 
            action.fill);
        break;
}

What just happened?

We added a new menu item to the Tool menu to draw circles using the context's arc() method.

Open the application and give it a try. Now we have a pretty decent collection of drawing tools in our application. We can make some more sophisticated drawings with all different colors and opacities rather than just black scribbles.

What just happened?

Have a go hero

Try adding your own drawing tool, such as a triangle or some other shape. Implement the drawing of the shape in the Canvas2D object then add a menu item to the toolbar.

Pop quiz

Q1. What unit is used to define the angle when drawing arcs?

  1. Degrees
  2. Units
  3. Radians
  4. Arcs

Q2. What context method is used to draw a path to the canvas?

  1. drawPath()
  2. stroke()
  3. draw()
  4. endPath()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.175.182