Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5: Fill circle/arc by percentage

Here is my pseudo code:

var percentage = 0.781743; // no specific length
var degrees = percentage * 360.0;
var radians = degrees * Math.PI / 180.0;

var x = 50;
var y = 50;
var r = 30;
var s = 1.5 * Math.PI;

var context = canvas.getContext('2d');
context.beginPath();
context.lineWidth = 5;
context.arc(x, y, r, s, radians, false);
context.closePath();
context.stroke();

I'm using the KineticJS library to control the shapes I make and redraw them as necessary. My problem is that the above code does not work at all. I assume I have the math incorrect, because if I change radians to something like 4.0 * Math.PI is draws the entire circle.

I've been using HTML5 Canvas Arc Tutorial for reference.

like image 837
Nahydrin Avatar asked Jan 19 '12 19:01

Nahydrin


1 Answers

Your code works just fine, but you have a starting angle that ought to be zero to get what you expect. Here's working code:

http://jsfiddle.net/HETvZ/

I think your confusion is from what starting angle does. It does not mean that it starts at that point and then adds endAngle radians to it. It means that the angle starts at that point and ends at the endAngle radians point absolutely.

So if you startAngle was 1.0 and endAngle was 1.3, you'd only see an arc of 0.3 radians.

If you want it to work the way you're thinking, you're going to have add the startAngle to your endAngle:

context.arc(x, y, r, s, radians+s, false);

Like in this example: http://jsfiddle.net/HETvZ/5/

like image 64
Simon Sarris Avatar answered Sep 30 '22 13:09

Simon Sarris