本意是打算写一个类似
f2
的半圆进度条,但是感觉小程序中引入太难调了,所以就自己用canvas随便画了一个实现了类似的效果。
最终效果图
wxml
<view class="top-box">
<canvas class="canvas-box" canvas-id='canvas'></canvas>
<view class="nx" style="left:{{(app.globalData.windowWidth)/2 - 50}}px;top: 140px;">{{nx}}%</view>
</view>
js
onReady: function () {
this.initCanvas()
},
initCanvas() {
let windowsWidth = app.globalData.windowWidth
let offset = 0.1 // 偏移
let r = 140 // 半径
const ctx = wx.createCanvasContext('canvas')
ctx.arc(windowsWidth / 2, 175, r, Math.PI * 1 - offset, computedC(1))
ctx.setStrokeStyle('#F8F9FC')
ctx.setLineCap('round')
ctx.setLineWidth(10)
ctx.stroke()
ctx.draw(true)
let x = 0
let ex = util.dayForMonth(new Date())
let timer = setInterval(()=>{
const ctxs = wx.createCanvasContext('canvas')
if(x >= ex){
clearInterval(timer)
}
this.setData({
nx:(x * 100).toFixed(1)
})
ctxs.arc(windowsWidth / 2, 175, r, Math.PI * 1 - offset, computedC(x))
ctxs.setLineWidth(10)
ctxs.setLineCap('round')
ctxs.setStrokeStyle('#07C160')
ctxs.stroke()
ctxs.draw(true)
x += 0.001
},5)
const ctxfont = wx.createCanvasContext('canvas')
ctxfont.setFontSize(20)
ctxfont.setFillStyle('#fff')
ctxfont.setTextAlign('center')
ctxfont.setTextBaseline('middle')
ctxfont.fillText(`本月进度`, windowsWidth / 2, 110)
ctxfont.draw(true)
function computedC(num) {
return Math.PI * (num + 1) + offset
}
},
utils.js
const dayForMonth = date => {
function $in(array, value) {
return array.indexOf(value) !== -1
}
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const thx = [1, 3, 5, 7, 8, 10, 12]
const twx = [4, 6, 9, 11]
if ($in(thx, month)) {
return (day/31).toFixed(4)
}
else if ($in(twx, month)) {
return (day/30).toFixed(4)
}
else{
if(year%4 === 0){
return (day/29).toFixed(4)
}else{
return (day/28).toFixed(4)
}
}
}
wxss
.top-box{
display: flex;
margin: 0 auto;
border-radius: 1%;
color: #fff;
width: 100vw;
height: 220px;
background-image: linear-gradient(#FF8B00, #FFCE00);
}
.canvas-box{
display: flex;
margin: 0 auto;
width: 100%;
height: 220px;
}
.nx{
position: absolute;
width: 100px;
text-align: center;
color: #fff;
font-size: 40px;
font-family: bold;
}