微信小程序canvas實現環形漸變
本文實例為大傢分享瞭微信小程序canvas實現環形漸變的具體代碼,供大傢參考,具體內容如下
這個例子是在微信小程序中寫的
效果圖
後端返回的數據格式,需要的隻有otherInfo裡面的數據
wxml
<view> <canvas class="progress_bg" canvas-id="{{otherInfo.bgid}}"> </canvas> <canvas class="progress_canvas" canvas-id="{{otherInfo.pgid}}"> </canvas> </view> <view class="progress_text"> <text class='progress_info'> {{otherInfo.sumPointNumber || 0}}分</text> </view>
js
data:{ otherInfo: { bgid: "bgid", pgid: "pgid", sumPointNumber: 100 // 默認圓環顯示的區域,全部顯示是100 } }
根據接口獲取數據,我隻截取瞭需要的部分,賦值到data裡面的otherInfo
下面是重要的canvas部分
用arc()方法創建圓,起始角設置為 0,結束角設置為 2*Math.PI(PI就是圓周率π,PI是弧度制的π,也就是180°,所以,Math.PI = 3.14 = 180°,PI是一個浮小數)
drawProgressbg() { let w = wx.getSystemInfoSync().screenWidth; let that = this; let ctx = wx.createCanvasContext(that.data.otherInfo.bgid) ctx.setLineWidth(8 * w / 375); ctx.setStrokeStyle('#DDEDFA'); ctx.setLineCap('round'); ctx.beginPath(); ctx.arc(80 * w / 375, 80 * w / 375, 65 * w / 375, 0, 2 * Math.PI, false); ctx.stroke(); ctx.draw(); }, drawCircle() { let w = wx.getSystemInfoSync().screenWidth; let that = this; let context = wx.createCanvasContext(that.data.otherInfo.pgid); context.setLineWidth(8 * w / 375); // context.setStrokeStyle('#55A5E6'); 不漸變的背景色 // 環形漸變的背景色 var my_gradient = context.createLinearGradient(0, 0, 200, 0); my_gradient.addColorStop(1, "#FA6400"); my_gradient.addColorStop(0, "#FFECAF"); context.strokeStyle = my_gradient; context.setLineCap('round'); context.beginPath(); context.arc(80 * w / 375, 80 * w / 375, 65 * w / 375, -Math.PI / 2, that.data.otherInfo.sumPointNumber / 50 * Math.PI - Math.PI / 2, false); context.stroke(); context.draw() }, onLoad: function (options) { this.getList() // 獲取的數據 this.drawProgressbg(); this.drawCircle() },
wxss
.progress_bg { position: absolute; left: 30%; width: 300rpx; height: 300rpx; z-index: 9; } .progress_canvas { left: 30%; width: 300rpx; height: 300rpx; z-index: 9; } .progress_text { display: flex; align-items: center; justify-content: center; margin-top: -23%; } .progress_info { letter-spacing: 2rpx; color: #000; font-weight: 600; font-size: 38rpx; }
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。