先上效果

image.png
再貼代碼
/**
* 領(lǐng)取進(jìn)度條
* @param {Int} num
* @param {String} elId
*/
function canvasPercentage(num, elId) {
// 計(jì)算百分比
var percentage = parseInt(num) / 100 * 80;
// 獲取元素
var divEl = document.getElementById(elId);
divEl.style = 'text-align: center;width:100%;heigth:50px;position: relative;';
divEl.innerHTML = '';
// 創(chuàng)建canvas
var canvasEl = document.createElement('canvas');
canvasEl.style.transform = 'rotate(-143deg)';
canvasEl.height = 50;
canvasEl.width = 50;
divEl.appendChild(canvasEl);
// 創(chuàng)建h3
var h3El = document.createElement('h3');
h3El.innerHTML = '已搶';
h3El.style = 'color:#f23030;position: absolute;width: 100%;top: 18px;line-height: 0;font-size: 11px;';
divEl.appendChild(h3El);
// 創(chuàng)建small
var smallEl = document.createElement('small');
smallEl.innerHTML = '0%';
smallEl.style = 'color:#f23030;position: absolute;display: block;width: 100%;text-align: center;top: 25px;left: 0px;';
divEl.appendChild(smallEl);
// 獲取canvas 上下文
var ctx = canvasEl.getContext('2d');
// Canvas中心點(diǎn)x軸坐標(biāo)
var centerX = canvasEl.width / 2;
// Canvas中心點(diǎn)y軸坐標(biāo)
var centerY = canvasEl.height / 2;
// 將360度分成100份,那么每一份就是rad度
var rad = Math.PI * 2 / 100;
// 起點(diǎn)
var speed = 0;
var drawCircle = function (ctxs, percent) {
// 畫白色的靜態(tài)圓
ctxs.save();
ctxs.strokeStyle = "#ffb8b8";
ctxs.lineWidth = 4;
ctxs.beginPath();
ctxs.arc(centerX, centerY, 20, -1.5707963267948966, 3.4557519189487547, false);
ctxs.stroke();
ctxs.closePath();
ctxs.restore();
// 畫進(jìn)度環(huán)
ctxs.save();
ctxs.strokeStyle = "#f23030";
ctxs.lineWidth = 4;
ctxs.beginPath();
ctxs.arc(centerX, centerY, 20, -Math.PI / 2, -Math.PI / 2 + percent * rad, false)
ctxs.stroke();
ctxs.closePath();
ctxs.restore();
}
var animate = function () {
window.requestAnimationFrame(function () {
if (speed < percentage) {
animate();
}
});
ctx.clearRect(0, 0, canvasEl.width, canvasEl.height);
speed += 1;
drawCircle(ctx, speed);
}
var countDown = function () {
var i = 0;
count[elId] = setInterval(function () {
if (i <= num) {
document.getElementById(elId).children[2].innerHTML = i + '%';
// this.smallEl.innerHTML = i + '%';
i++;
} else {
clearInterval(count[elId]);
}
}, 16);
}
countDown();
animate();
}