h5圓形進度條
元件封裝檔案 circlebar.js 程式碼如下:
(function() {
var context, centerX, centerY;
var rad = Math.PI * 2 / 100; //將360度分成100份,每份為rad度
var radius = 25; //預設半徑
var lineWidth = 5; //預設線寬
var speed = 0; //預設初始載入值
var value = 0;
//繪製有值的顏色圈環
function valueCircle(n) {
context.save();
context.strokeStyle = "#19AC55"; //設定描邊樣式
context.lineWidth = lineWidth; //設定線寬
context.beginPath(); //路徑開始
context.arc(centerX, centerY, radius, -Math.PI / 2, -Math.PI / 2 + n * rad, false); //用於繪製圓弧context.arc(x座標,y座標,半徑,起始角度,終止角度,順時針/逆時針)
context.stroke(); //繪製
context.closePath(); //路徑結束
context.restore();
}
//繪製背景圓環圈
function bgCircle() {
context.save();
context.beginPath();
context.lineWidth = lineWidth; //設定線寬
context.strokeStyle = "#ECEAE9";
context.arc(centerX, centerY, radius, 0, Math.PI * 2, false);
context.stroke();
context.closePath();
context.restore();
}
//百分比文字繪製
function text(n) {
context.save(); //save和restore可以保證樣式屬性只運用於該段canvas元素
context.strokeStyle = "#ECEAE9"; //設定描邊樣式
context.font = "bold 17px Arial"; //設定字型大小和字型
//繪製字型,並且指定位置
context.fillStyle = "#19AC55";
context.fillText(n.toFixed(0) + "%", centerX - 18, centerY + 5);
context.stroke(); //執行繪製
context.restore();
}
var circlebar = function(id, v, radi, lWidth) {
var canvas = document.getElementById(id); //獲取canvas元素
centerX = canvas.width / 2; //Canvas中心點x軸座標
centerY = canvas.height / 2; //Canvas中心點y軸座標
if(v) {
value = v;
}
if(radi) {
radius = radi;
}
if(lWidth) {
lineWidth = lWidth;
}
context = canvas.getContext('2d'); //獲取畫圖環境,指明為2d
//動畫迴圈
(function drawFrame() {
if(speed < value) {
window.requestAnimationFrame(drawFrame);
}
context.clearRect(0, 0, canvas.width, canvas.height);
bgCircle();
text(speed);
valueCircle(speed);
//if(speed > 100) speed = 0;
speed += 1;
}());
}
window.circlebar = circlebar;
})();
使用方法:
1.在對應html引入circlebar.js檔案;
2.在對應div新增 如:
<div>
<canvas id="canvas" width="260px" height="260px"></canvas>
</div>
注意: canvas的width和height屬性值不得小於直徑和條形寬度之和。
3.在<script> 裡面 新增 new circlebar("canvas",70); //此處設定的進度值為70,半徑和條形寬度為預設值,分別為25 、5.