HTML5: Fill circle/arc by percentage

后端 未结 2 512
时光取名叫无心
时光取名叫无心 2021-02-10 15:42

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;
         


        
相关标签:
2条回答
  • 2021-02-10 16:20

    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/

    0 讨论(0)
  • 2021-02-10 16:26

    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);
    
    0 讨论(0)
提交回复
热议问题