微信小程序新版canvas画圆形进度条
微信小程序的canvas。。一言难尽
先差不多上个效果图吧
网上其实能找到挺多教程,但注意!!!都是很久之前的写法,有些方法已经被废除了,像wx.createCanvasContext,ctx.draw(),另外draw()文档上还没更新,文档上显示还能用,真的太坑了,而且还有很多绘图时使用的方法也更换了,具体看小程序文档
另外其实现在小程序画圆跟H5用canvas差不多的
具体看这个
HTML canvas arc() 方法https://www.w3school.com.cn/tags/canvas_arc.asp上一波代码吧,改动挺多的对比以前,其实就是获取ctx根据小程序文档来改进的,还有关于画圆变成椭圆的问题其实我自己的解决办法就是不给它加高度宽度,直接用半径绘制,还知道一种方法就是直接在canvas标签上面加height:100;width:100
WXML
<view class="progress">
<canvas type="2d" class="progress_bg" canvas-id="canvasProgressBg" id="ProgressBgId"></canvas>
<canvas type="2d" class="progress_canvas" canvas-id="canvasProgress" id="ProgressId"></canvas>
<view class="progress_text">
<image class="progress_img" src="/img/success.png" mode="widthFix"></image>
<view class="progress_num">{{progressNum}}</view>
</view>
</view>
JS
// pages/downLoad/downLoad.js
Page({
/**
* 页面的初始数据
*/
data: {
progressNum:'10%',
screenWidth:0,
step:0
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
wx.getSystemInfo({
success: (res) => {
this.setData({
screenWidth:res.screenWidth
})
},
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
this.drawProgressBg()
this.drawCircle(2)
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
drawProgressBg(){
wx.createSelectorQuery()
.select("#ProgressBgId")
.fields({
node: true,
size: true,
})
.exec(this.initBg.bind(this))
},
initBg(res){
const canvas = res[0].node
const ctx = canvas.getContext('2d')
ctx.lineWidth = 4
ctx.strokeStyle = "#F5F6F7"
ctx.lineCap = "round"
ctx.beginPath()
ctx.arc(148.5,75,this.calScreen(36),0,2*Math.PI,false);
ctx.stroke();//对当前路径进行描边
},
drawCircle(step){
this.setData({
step
})
wx.createSelectorQuery()
.select("#ProgressId")
.fields({
node: true,
size: true,
})
.exec(this.initCircle.bind(this))
},
initCircle(res){
const canvas = res[0].node
const ctx = canvas.getContext('2d')
ctx.lineWidth = 4
ctx.strokeStyle = "#2AD18B"
ctx.lineCap = "round"
ctx.beginPath()
ctx.arc(148.5,75,this.calScreen(36),-Math.PI*0.5,this.data.step*Math.PI-2*Math.PI,false);
ctx.stroke();//对当前路径进
},
//根据屏幕宽度计算当前半径使得画出来的圆能自适应
calScreen(val){
var screenWidth = this.data.screenWidth
return val*(screenWidth/375)
}
})
WXSS
.content .canvas{
display: flex;
justify-content: center;
}
.content .canvas .progress{
position: relative;
display: flex;
align-items: center;
justify-content: center;
background-color: #fff;
}
.content .canvas .progress .progress_bg{
position: absolute;
}
.content .canvas .progress .progress_text{
position: absolute;
text-align: center;
}
.content .canvas .progress .progress_text .progress_img{
width: 34rpx;
}
.content .canvas .progress .progress_text .progress_num{
color: #2AD18B;
font-size: 28rpx;
}
顺便提一下获取小程序的下载进度可以看文档这一个地方
DownloadTask | 微信开放文档https://developers.weixin.qq.com/miniprogram/dev/api/network/download/DownloadTask.html对了代码可能写的菜,目前还在实习中,还需努力学习觉得有用就点个赞吧