小程序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;
}

 效果圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM