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 values I know now of the triangle are: the hypotenuse=100px(the radius), the angle=7 degrees(277-270).
sin(7) = o/100; 0.1219 = o/100; o = 12.2;
Therefore the y point is 12.2 (for my sakes 0,0 is the top left corner so its really midY-x = 100-12.2 = 87.8; (is that correct?)
Now to determine the x pos, I use cos(is that correct?).
cos(7) = a/100; a = 99.25;
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);
}
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