最近做一個小程序,有用到canvas畫圓環形進度條,效果圖就是上圖了。
爲了方便日後使用,我已經封裝了一個獨立的js文件。
先簡單說一下實現流程,封裝好的文件下載地址:https://github.com/SuperDalu/wxCanvas.git
<canvas canvas-id="runCanvas" id="runCanvas" class='canvas'></canvas>
const ctx2 = wx.createCanvasContext(id);
wx.createSelectorQuery().select('#'+id).boundingClientRect(function (rect) { //監聽canvas的寬高 console.log(rect); var w = parseInt(rect.width / 2); //獲取canvas寬的的一半 var h = parseInt(rect.height / 2); //獲取canvas高的一半, }).exec();
run(c, w, h) { //c是圓環進度百分比 w,h是圓心的座標 let that = this; var num = (2 * Math.PI / 100 * c) - 0.5 * Math.PI; //圓環的繪製 ctx2.arc(w, h, w - 8, -0.5 * Math.PI, num); //繪製的動作 ctx2.setStrokeStyle("#ff5000"); //圓環線條的顏色 ctx2.setLineWidth("16"); //圓環的粗細 ctx2.setLineCap("butt"); //圓環結束斷點的樣式 butt爲平直邊緣 round爲圓形線帽 square爲正方形線帽 ctx2.stroke(); //開始繪製百分比數字 ctx2.beginPath(); ctx2.setFontSize(40); // 字體大小 注意不要加引號 ctx2.setFillStyle("#ff5000"); // 字體顏色 ctx2.setTextAlign("center"); // 字體位置 ctx2.setTextBaseline("middle"); // 字體對齊方式 ctx2.fillText(c + "%", w, h); // 文字內容和文字座標 ctx2.draw(); },
實現動畫效果。
實現動畫效果其實使用定時器控制run方法一直執行。
canvasTap(start, end, time, w, h) { //傳入開始百分比和結束百分比的值,動畫執行的時間,還有圓心橫縱座標 var that = this; start++; if (start > end) { return false; } that.run(start, w, h); //調用run方法 setTimeout(function () { that.canvasTap(start, end, time, w, h); }, time); },
這就基本實現了圓環進度條的繪製。
demo和封裝好的js文件請到GitHub上下載,下載地址:https://github.com/SuperDalu/wxCanvas.git
小程序方法的封裝和調用我在之前的博客中有寫到過,博客地址:https://blog.csdn.net/weixin_41257563/article/details/82792194