HTML5: Fill circle/arc by percentage
Asked Answered
I

2

6

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.

Intuition answered 19/1, 2012 at 19:17 Comment(0)
F
12

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/

Foxglove answered 19/1, 2012 at 19:25 Comment(0)
A
0

Your code is just fine. you need to have: s=0 i.e. starting point must be zero. and if you want circle to start drawing at top you can use: context.rotate(-90 * Math.PI / 180); but after rotating you will have to check arc()'s x,y arguments. i used it like:

context.rotate(-90 * Math.PI / 180);
context.arc(-200, 200, 150, startPoint, radian, false); 
context.lineWidth = 20;
context.strokeStyle = '#b3e5fc';
context.stroke();
context.closePath();

after this i needed to display percentage in text form so i did:

context.rotate(90 * Math.PI / 180);
context.fillStyle = '#1aa8ff';
context.textAlign = 'center';
context.font = "bold 76px Verdana";;
context.textBaseline = "middle";
context.fillText("50%", 200, 200);
Ansela answered 17/7, 2017 at 19:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.