微信小程序canvas實現(xiàn)儀表盤動畫

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ù)字(虛線長度與虛線間距)

number offset
虛線偏移量

繪制底部灰色背景儀表盤代碼:

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)

微信小程序下載文件有最大10M的限制,如果要進行大文件下載需要平臺側進行拆分
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容