效果如下图:
代码如下
<canvas class="pull-right list_canvas" width="200" height="200" style="height:100px;width:100px"></canvas>
function drawarc(percent, ctx, sR) {
if (percent < 0 || percent > 100) {
return;
}
if (sR < Math.PI / 2 || sR >= 3 / 2 * Math.PI) {
return;
}
var canvas = ctx,
cxt = canvas.getContext('2d'),
cWidth = canvas.width,
cHeight = canvas.height,
baseColor = '#fff1ef',
coverColor = '#ff6c64',
txtcolor = '#ff6c64',
PI = Math.PI,
sR = sR || 1 / 2 * PI; // 默认圆弧的起始点弧度为π/2
var finalRadian = sR + ((PI + (PI - sR) * 2) * percent / 100); // 红圈的终点弧度
var step = (PI + (PI - sR) * 2) / 100; // 一个1%对应的弧度大小
var text = 0
window.requestAnimationFrame(paint);
w = window.innerWidth * 0.12 / 2;
function paint() {
cxt.clearRect(0, 0, cWidth, cHeight);
var endRadian = sR + text * step; //动画起始位置
var lGrd = cxt.createLinearGradient(endRadian, endRadian, 0, cHeight);
// lGrd.addColorStop(0, coverColor);
// lGrd.addColorStop(0.3, coverColor);
lGrd.addColorStop(1, coverColor);
// 画灰色圆弧
drawCanvas(cWidth / 2, cHeight / 2, w * 2, sR, sR + (PI + (PI - sR) * 2), baseColor, 8);
// 画蓝色圆弧
drawCanvas(cWidth / 2, cHeight / 2, w * 2, -sR, endRadian - sR * 2, lGrd, 8);
cxt.fillStyle = txtcolor;
cxt.font = '24px PT Sans';
var textWidth = cxt.measureText('抢').width;
cxt.fillText('抢', cWidth / 2 - textWidth / 2, cHeight / 2 + 9);
text++;
if (endRadian.toFixed(2) < finalRadian.toFixed(2)) {
window.requestAnimationFrame(paint);
}
}
function drawCanvas(x, y, r, sRadian, eRadian, color, lineWidth) {
cxt.beginPath();
cxt.lineCap = "round";
cxt.strokeStyle = color;
cxt.lineWidth = lineWidth;
cxt.arc(x, y, r, sRadian, eRadian, false);
cxt.stroke();
}
}
var lineColor = document.querySelectorAll(".list_canvas"); //获取元素数组
drawarc(50, lineColor[0]);
这时候会遇到当数值在96%-99%时,效果上看起来是100%,可以做如下处理。
function drawy() {//优化动画
var lineColor = document.querySelectorAll(".list_canvas"); //获取元素数组
for (i = 0; i < lineColor.length; i++) {
if ($scope.list[i] && lineColor[i]) {
CurrentWidth1 = $scope.list[i].currentSchedule * 100;
if (CurrentWidth1 < 100) {
if (CurrentWidth1 >= 97 && CurrentWidth1 < 100) {
CurrentWidth1 = 96;
}
drawarc(CurrentWidth1.toFixed(0), lineColor[0])
} else {
i = i//已回款的标 购买总金额为0(currentLoanPrice ) 出现两个图标重叠现象
}
} else {
return false;
}
}
}
drawy();