美文网首页
微信小程序canvas实现仪表盘动画

微信小程序canvas实现仪表盘动画

作者: baxiamali | 来源:发表于2019-10-15 19:44 被阅读0次
1571137725714.jpg

效果图如上图所示,上篇文章分享了用css clip 实现圆盘loading。
但是由于动画效果有虚线和渐变,所以综合考虑,选择用canvas实现。

涉及知识点:

绘制圆弧:

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
一组描述交替绘制线段和间距(坐标空间单位)长度的数字(虚线长度与虚线间距)

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是为了和指针旋转动画时间一致引入的参数。
指针动画直接用css即可实现。transform:rotate({{angle}}deg)

微信小程序下载文件有最大10M的限制,如果要进行大文件下载需要平台侧进行拆分

相关文章

网友评论

      本文标题:微信小程序canvas实现仪表盘动画

      本文链接:https://www.haomeiwen.com/subject/mcqemctx.html