如何绘制圆形轮廓的百分比

时间:2013-08-10 12:59:14

标签: javascript html5

我想在多个圆圈周围绘制一条线,但只有一定比例。具体来说,我需要动态输入特定的百分比来绘制这些圆圈,所以我当前的开始和结束角度的方法会导致问题:

var data = [
    {id:'firefox', angle:90-90},
    {id:'chrome', angle:144},
    {id:'ie', angle:72},
    {id:'opera', angle:28.8},
    {id:'safari', angle:7.2}
];
data.forEach(function(e){
    var canvas = document.getElementById(e.id);
    var context = canvas.getContext('2d');
    context.beginPath();
    context.arc(64, 64, 60, 1.5*Math.PI, e.angle, true);
    context.lineWidth = 8;
    context.lineCap = "round";
    context.strokeStyle = '#c5731e';
    context.stroke();
});

1 个答案:

答案 0 :(得分:1)

var data = [
    {id:'firefox', percent:100},
    {id:'chrome', percent:50},
    {id:'ie', percent:25},
    {id:'opera', percent:33.33},
    {id:'safari', percent:66.66}
];
data.forEach(function(e){
    var canvas = document.getElementById(e.id);
    var context = canvas.getContext('2d');

    var startAngle = 1.5 * Math.PI;                  //Top of the arc
    var endAngle = (2 * Math.PI) / 100 * e.percent;  //"2 * PI" = 360° 
                                                     //and "/ 100 * e.percent" = e.percent%

    context.beginPath();
    context.arc(64, 64, 60, startAngle, startAngle - endAngle, true);
                                                     //substract(!) end from start, because we are going ANTIclockwise!
    context.lineWidth = 8;
    context.lineCap = "round";
    context.strokeStyle = '#c5731e';
    context.stroke();
});

见评论;)

文件:

http://www.html5canvastutorials.com/tutorials/html5-canvas-arcs/