遇到的坑
- 使用普通canvas需要延迟设置
draw()
stroke()
才生效。 - 使用
canvas2d
在微信小程序的开发者工具上表现为固定在屏幕上,不随容器滚动,但是手机表现正常。 - 记住: 在组件中获取实例需要使用
in(this)
。如 const ctx = uni.createCanvasContext('myCanvas',this)
,const query = uni.createSelectorQuery().in(this)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d0068a79caaae99e88cb28e26682e18a.png)
组件代码
<template>
<div class="com-container">
<canvas canvas-id="canvas" id="canvas" class="my-canvas" type="2d"></canvas>
</div>
</template>
<script>
export default {
props: {
progress: {
type: Number,
default: 50
},
innerText: {
type: String,
default: '850'
}
},
data() {
return {
ctx: null
}
},
mounted() {
this.getCanvas()
},
methods: {
getCanvas() {
const query = uni.createSelectorQuery().in(this)
query.select('#canvas')
.fields({ node: true, size: true })
.exec((res) => {
const canvas = res[0].node
canvas.width = 120
canvas.height = 120
const ctx = canvas.getContext('2d')
this.ctx = ctx
})
setTimeout(() => {
this.drawTrack()
this.drawProgress(this.progress)
this.drawText(this.innerText)
}, 500);
},
drawTrack() {
this.ctx.save()
this.ctx.beginPath()
this.ctx.lineCap = "round"
this.ctx.lineWidth = 8
this.ctx.strokeStyle = "#dde1ed"
this.ctx.arc(60, 60, 50, 0, 2 * Math.PI)
this.ctx.stroke()
this.ctx.closePath()
this.ctx.restore()
},
drawProgress(num) {
this.ctx.save()
this.ctx.beginPath()
this.ctx.lineCap = "round"
this.ctx.lineWidth = 8
this.ctx.strokeStyle = "#5f94f0"
this.ctx.arc(
60,
60,
50,
-Math.PI / 2,
-Math.PI / 2 + ((2 * num) / 100) * Math.PI,
true
)
this.ctx.stroke()
this.ctx.closePath()
this.ctx.restore()
},
drawText(num) {
this.ctx.save()
this.ctx.fillStyle = "#6094F3"
this.ctx.font = "33px Helvetica"
this.ctx.textAlign = "center"
this.ctx.fillText(num, 60, 70)
this.ctx.restore()
}
}
}
</script>
<style lang='scss' scoped>
.com-container {
width: 240rpx;
height: 240rpx;
.my-canvas {
width: 100%;
height: 100%;
z-index: 999;
}
}
</style>