
1571137725714.jpg
效果圖如上圖所示,上篇文章分享了用css clip 實現(xiàn)圓盤loading。
但是由于動畫效果有虛線和漸變,所以綜合考慮,選擇用canvas實現(xiàn)。
涉及知識點:
繪制圓弧:
CanvasContext.arc(number x, number y, number r, number sAngle, number eAngle, boolean counterclockwise)

下載.png
針對 arc(100, 75, 50, 0, 1.5 * Math.PI)的三個關鍵坐標如下:
綠色: 圓心 (100, 75)
紅色: 起始弧度 (0)
藍色: 終止弧度 (1.5 * Math.PI)
繪制虛線:
CanvasContext.setLineDash(Array.<number> pattern, number offset)
Array.<number> pattern
一組描述交替繪制線段和間距(坐標空間單位)長度的數(shù)字(虛線長度與虛線間距)
繪制底部灰色背景儀表盤代碼:
drawBack:function(){
ctx.beginPath();
ctx.arc(120, 120, 110, (5 / 6) * Math.PI, (13 / 6) * Math.PI)
ctx.strokeStyle = '#4e6a68';
ctx.lineWidth = 8;
ctx.setLineDash([0]);
ctx.stroke();
ctx.beginPath();
ctx.arc(120, 120, 119, (5 / 6) * Math.PI, (13 / 6) * Math.PI)
ctx.strokeStyle = '#4e6a68';
ctx.lineWidth = 2;
ctx.setLineDash([2, 12]);
ctx.stroke();
ctx.draw();
},
繪制填充顏色代碼:
drawRight:function(start,end){
now = start;
let that = this;
canvasInterval = setInterval(function () {
if (now > end) {
clearInterval(canvasInterval);
} else {
that.draw(now);
now += (end-start)/(time/5);
}
}, 5);
},
drawLeft: function (start, end) {
now = start;
let that = this;
canvasInterval = setInterval(function () {
if (now < end) {
clearInterval(canvasInterval);
} else {
that.draw(now);
now -= (start - end) / (time / 5);
}
}, 5);
},
draw: function (now){
//繪制背景底盤
ctx.beginPath();
ctx.arc(120, 120, 110, (5 / 6) * Math.PI, (13 / 6) * Math.PI)
ctx.strokeStyle = '#4e6a68';
ctx.lineWidth = 8;
ctx.setLineDash([0]);
ctx.stroke();
ctx.beginPath();
ctx.arc(120, 120, 119, (5 / 6) * Math.PI, (13 / 6) * Math.PI);
ctx.strokeStyle = '#4e6a68';
ctx.lineWidth = 2;
ctx.setLineDash([2, 12]);
ctx.stroke();
//繪制填充顏色部分
ctx.beginPath();
ctx.strokeStyle = '#18c9b2';
ctx.arc(120, 120, 110, (5 / 6) * Math.PI, now * Math.PI);
ctx.lineWidth = 8;
ctx.setLineDash([0]);
ctx.stroke();
ctx.beginPath();
ctx.arc(120, 120, 119, (5 / 6) * Math.PI, now * Math.PI);
ctx.lineWidth = 2;
ctx.setLineDash([2, 12]);
ctx.stroke();
ctx.draw();
},
time是為了和指針旋轉動畫時間一致引入的參數(shù)。
指針動畫直接用css即可實現(xiàn)。transform:rotate({{angle}}deg)