小程序canvas实现环形进度条

不多说直接上代码:

export default{ 
  data: {
  },
  options:{
    drawerbg:function(id){
      let ctx = wx.createCanvasContext(id);
      wx.createSelectorQuery().select('#'+id).boundingClientRect(function (rect) { //监听canvas的宽高
        var w = parseInt(rect.width / 2); //获取canvas宽的的一半
        var h = parseInt(rect.height / 2); //获取canvas高的一半,
        ctx.arc(w, h, w - 2.5, 0.75 * Math.PI, 2.25 * Math.PI); //绘制圆形弧线
        ctx.setStrokeStyle("#dddddd"); //设置填充线条颜色
        ctx.setLineWidth("5");     //设置线条宽度
        ctx.setLineCap("round");        //设置线条端点样式
        ctx.stroke();     //对路径进行描边,也就是绘制线条。
        ctx.draw();       //开始绘制
      }).exec();
    },
    draw: function (id, val1,val2,color,time) {
      let ctx2 = wx.createCanvasContext(id);
      let percent = Math.round((val1/val2)*100);
      wx.createSelectorQuery().select('#'+id).boundingClientRect(function (rect) { //监听canvas的宽高
        var w = parseInt(rect.width / 2); //获取canvas宽的的一半
        var h = parseInt(rect.height / 2); //获取canvas高的一半,
        var num = (1.5/100*percent+0.75) * Math.PI;
        console.log(num)
        ctx2.arc(w, h, w-2.5, 0.75 * Math.PI, num); //每个间隔绘制的弧度
        ctx2.setStrokeStyle(color);
        ctx2.setLineWidth("5");
        ctx2.setLineCap("round");
        ctx2.stroke();
        ctx2.beginPath();
        ctx2.setFontSize(14); //注意不要加引号
        ctx2.setFillStyle("#666666");
        ctx2.setTextAlign("center");
        ctx2.setTextBaseline("middle");
        ctx2.fillText('当前进度', w, h);
        ctx2.setFillStyle(color);
        ctx2.fillText(val1, w-13, h+20);
        ctx2.setFillStyle("#666666");
        ctx2.fillText('/', w, h+20);
        ctx2.fillText(val2, w+13, h+20);
        ctx2.draw();
      }).exec();
    },
  } 
}

 

在pages的js文件中引入:

import Canvas from './canvas.js'
Page({
  ...Canvas.options,
  /**
   * 页面的初始数据
   */
  data: {
    ...Canvas.data,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  onShow:function(){
    this.drawerbg('bgcanvas1');
    this.draw('runCanvas1',10,10,'#376EFF',1000);
    this.drawerbg('bgcanvas2');
    this.draw('runCanvas2',4,10,'#E33A34',1000);

  }
})

 

wxml:

  
<view class='canvasBox' wx:for="{{[1,2]}}">
  <canvas canvas-id="bgcanvas{{index+1}}" id="bgcanvas{{index+1}}" class='canvas'>canvas>
  <canvas canvas-id="runCanvas{{index+1}}" id="runCanvas{{index+1}}" class='canvas'>canvas>
view>

 

wxss:

/* pages/canvasDemo/canvasDemo.wxss */
.canvasBox{
  width: 100px;
  height:100px;
  position: relative;
}
.canvas{
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  margin: auto auto;
  z-index: 99;
}

 效果图:

小程序canvas实现环形进度条_第1张图片

 

你可能感兴趣的:(小程序canvas实现环形进度条)