示例效果圖如下:

1、先來制作簡單HTML代碼結構:
<div class="box">
<ul>
<li>
<canvas id="one" width="200" height="200"></canvas>
</li>
<li>
<canvas id="two" width="200" height="200"></canvas>
</li>
<li>
<canvas id="three" width="200" height="200"></canvas>
</li>
</ul>
</div>
2、再是CSS樣式代碼:
body {
margin: 0;
padding: 50px 0;
background-color: #444;
}
ul,li {
list-style: none;
margin: 0;
padding: 0;
}
ul li {
float: left;
width: 33%;
text-align: center;
}
3、具體JS代碼實現+注釋如下:
function drawCircle(_options){
var options = _options || {}; //獲取或定義options對象;
options.angle = options.angle || 1; //定義默認角度1為360度(角度范圍 0-1);
options.color = options.color || '#fff'; //定義默認顏色(包括字體和邊框顏色);
options.lineWidth = options.lineWidth || 10; //定義默認圓描邊的寬度;
options.lineCap = options.lineCap || 'square'; //定義描邊的樣式,默認為直角邊,round 為圓角
var oBoxOne = document.getElementById(options.id);
var sCenter = oBoxOne.width / 2; //獲取canvas元素的中心點;
var ctx = oBoxOne.getContext('2d');
var nBegin = Math.PI / 2; //定義起始角度;
var nEnd = Math.PI * 2; //定義結束角度;
var grd = ctx.createLinearGradient(0, 0, oBoxOne.width, 0); //grd定義為描邊漸變樣式;
grd.addColorStop(0, 'red');
grd.addColorStop(0.5, 'yellow');
grd.addColorStop(1, 'green');
ctx.textAlign = 'center'; //定義字體居中;
ctx.font = 'normal normal bold 20px Arial'; //定義字體加粗大小字體樣式;
ctx.fillStyle = options.color == 'grd' ? grd : options.color; //判斷文字填充樣式為顏色,還是漸變色;
ctx.fillText((options.angle * 100) + '%', sCenter, sCenter); //設置填充文字;
/*ctx.strokeStyle = grd; //設置描邊樣式為漸變色;
ctx.strokeText((options.angle * 100) + '%', sCenter, sCenter); //設置描邊文字(即鏤空文字);*/
ctx.lineCap = options.lineCap;
ctx.strokeStyle = options.color == 'grd' ? grd : options.color;
ctx.lineWidth = options.lineWidth;
ctx.beginPath(); //設置起始路徑,這段繪制360度背景;
ctx.strokeStyle = '#D8D8D8';
ctx.arc(sCenter, sCenter, (sCenter - options.lineWidth), -nBegin, nEnd, false);
ctx.stroke();
var imd = ctx.getImageData(0, 0, 240, 240);
function draw(current) { //該函數實現角度繪制;
ctx.putImageData(imd, 0, 0);
ctx.beginPath();
ctx.strokeStyle = options.color == 'grd' ? grd : options.color;
ctx.arc(sCenter, sCenter, (sCenter - options.lineWidth), -nBegin, (nEnd * current) - nBegin, false);
ctx.stroke();
}
var t = 0;
var timer = null;
function loadCanvas(angle) { //該函數循環繪制指定角度,實現加載動畫;
timer = setInterval(function(){
if (t > angle) {
draw(options.angle);
clearInterval(timer);
}else{
draw(t);
t += 0.02;
}
}, 20);
}
loadCanvas(options.angle); //載入百度比角度 0-1 范圍;
timer = null;
}
4、代碼已封裝成函數,除了ID是必填選項,其它都可不填,使用默認值,展示三種調用方法如下:
drawCircle({
id: 'one',
color: '#0000ff',
angle: 0.5,
lineWidth: 5
});
drawCircle({
id: 'two',
angle: 0.75,
color: '#ff0000',
lineWidth: 12
});
drawCircle({
id: 'three',
angle: 1,
lineWidth: 15,
color: 'grd'
});
注:還可以在此基礎上加強擴展功能,如:設定寬高,多種展示樣式等!