HTML5: Fill Percent Circle / Arc

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 use the KineticJS library to manage the shapes that I create, and redraw them as needed. My problem is that the above code does not work at all. I assume that I have the wrong math, because if I change the radians to something like 4.0 * Math.PI , then I draw the whole circle.

I used the HTML5 Canvas Arc Tutorial for reference.

+4
source share
2 answers

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

http://jsfiddle.net/HETvZ/

I think your confusion is what makes the starting angle. This does not mean that it starts from this moment, and then adds endAngle radians to it. This means that the angle begins at this point and ends in the end. Radiants indicate absolutely.

So, if you had startAngle 1.0 and endAngle 1.3, you would only see an arc of 0.3 radians.

If you want it to work the way you think, you add startAngle to your endAngle:

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

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

+9
source

Your code is ok. you need to have: s = 0, that is, the starting point must be zero. and if you want the circle to start drawing from above, you can use: context.rotate (-90 * Math.PI / 180); but after the rotation you have to check the arguments arc () x, y. 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 that I needed to display the 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); 
0
source

Source: https://habr.com/ru/post/1391909/


All Articles