javascripthtmlalgorithmsvg

Algorithm: Function to resolve degrees to x,y for drawing SVG Pie Graphs


I am working with SVG graphics to draw Pie Graphs. I am given the degrees a pie graph should be - eg 277 degrees - and the diameter - eg 200px - and I need to draw a circle of 277 degrees.

With SVG graphics I need to resolve that 277 degrees to a point where that circle will end.

I am not the greatest with math, so I have come up with a formula/javascript function that will allow me to take a degrees value & come up with a x,y point of where the circle will end.

Will my Javascript function(at the bottom) correctly resolve a degrees to a correct point? Can you help me develop my algorithm to obtain the coordinate from a degree value? Or maybe there is an existing algorithm I can use that I dont know about?

My Algorithm: (Which I require help with)
So the values I am given are: Circle Diameter: 200px, Circle size: 277 degrees.

So the x,y coordinate of 277 degrees is 0.75,87.8. Is that correct?

So in code this algorithm would be:

function resolveToPoint( deg, diameter )
{
    if ( deg <= 0)
        return 0;

    var x     = 0;
    var y     = 0;
    var angle = 0;
    var rad   = diameter/2;
    var midX  = rad;
    var midY  = rad;

    if (deg <= 90)
        angle = 90 - deg;
    else if (deg <= 180)
        angle = deg - 90;
    else if (deg <= 270)
        angle = deg - 180;
    else if (deg <= 360)
        angle = deg - 270;

    // Q: Will I ALWAYS use cos to determine the x & sin for the x NO MATTER what quadrant the angle is in??
    x = Math.cos(angle) * rad;
    y = Math.sin(angle) * rad;

    if (deg <= 90)
    {
        x = midX + x;
        y = midY - y;
    }
    else if (deg <= 180)
    {
        x = midX + x;
        y = midY + y;
    }
    else if (deg <= 270)
    {
        x = midX - x;
        y = midY + y;
    }
    else if (deg <= 360)
    {
        x = midX - x;
        y = midY - y;
    }

    return {mX: x, mY: y};
}

Then I'll use it in a SVG like so:

function outputPiegraph( point, rad, diameter )
{  
    var svg = '<svg width="%spx" height=""%spx" id='pie' style="background-color: green;">
    <path d="M%spx,%spx L%spx, %spx A%spx,"%spx 1 1,1 %spx,%spx z"
     fill="red" stroke="blue" stroke-width="2" />"
</svg>';


    return sprintf(svg, diameter, diameter, point.mX, point.mY, rad, rad, rad, diameter);
}

Solution

  • This is simple conversion from polar to Cartesian coordinates:

    function resolveToPoint(deg, diameter) {
        var rad = Math.PI * deg / 180;
        var r = diameter / 2;
        return {mX: r * Math.cos(rad), mY: r * Math.sin(rad)};
    }
    

    http://en.wikipedia.org/wiki/Polar_coordinates#Converting_between_polar_and_Cartesian_coordinates