微信小程序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; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)