<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>
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; }
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; }
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' });