Search code examples
javascriptmathgeometrytrigonometrygraphing

Why is cosine used to calculate the x values and sine the y values for an arc?


I'm trying to understand the math on this raphael.js demo:

http://raphaeljs.com/pie.js

Checkout the sector method:

function sector(cx, cy, r, startAngle, endAngle, params) {
    var x1 = cx + r * Math.cos(-startAngle * rad),
        x2 = cx + r * Math.cos(-endAngle * rad),
        y1 = cy + r * Math.sin(-startAngle * rad),
        y2 = cy + r * Math.sin(-endAngle * rad);
    return paper.path(["M", cx, cy, "L", x1, y1, "A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2, "z"]).attr(params);
}

This is the actual demo: http://raphaeljs.com/pie.html

My math is a little rusty and I'm trying to understand the sector function - given the startAngle and endAngle parameters (each start and end point values between 0 and 360 drawing an arc), why does this function work?


Solution

  • It all depends on how you treat startAngle and endAngle. It looks like this is treating them as starting from horizontal to the right (i.e. an angle of 0 is pointing East) and going clockingwise (so an angle of 45 degrees is pointing South-East.

    Usually in mathematics we consider angles starting from the horizontal to the right, but increasing anti-clockwise... but if you ask a non-mathematician to draw an angle, they may well treat it from vertically up (i.e. North) increasing clockwise. This looks like it's taking a mixture :) There's no really "wrong" or "right" answer here - it's all a matter of definition.

    As pictures are popular, here are the three systems I've described, each assuming the line is of length r:

    Normal mathematics: anti-clockwise from x-axis

    First diagram
    (source: arachsys.com)

    Asking the man on the street to draw an angle (clockwise from y-axis)

    Second diagram

    The angles used by this code (clockwise from x-axis)

    Third diagram