1、首先在wxml裡建一個canvas
<canvas
type="2d"
id="canvas"
style="width: 223rpx; height: 94rpx; display: block; box-sizing: border-box; left: 0rpx; top: 0rpx"
></canvas>
2、在js裡添加方法
//畫弧線
drawCurve() {
// 通過 SelectorQuery 擷取 Canvas 節點
wx.createSelectorQuery().select('#canvas').node(function (res) {
console.log(res.node) // 節點對應的 Canvas 執行個體。
const canvas = res.node
const ctx = canvas.getContext('2d')
ctx.lineWidth=10
ctx.strokeStyle = 'red'
ctx.lineCap='round'
ctx.beginPath()
//arc(圓心x軸,圓心y軸,半徑機關像素,起始角度弧度制從x軸正方向開始,結束角度弧度制,true表示逆時針繪制)
ctx.arc(canvas.width / 2, canvas.height-ctx.lineWidth,canvas.height-(ctx.lineWidth*2), 0, 3.14926,true)
ctx.stroke()
}).exec()
},
//畫圓
drawCircle() {
// 通過 SelectorQuery 擷取 Canvas 節點
wx.createSelectorQuery().select('#canvas').node(function (res) {
console.log(res.node) // 節點對應的 Canvas 執行個體。
const canvas = res.node
const ctx = canvas.getContext('2d')
ctx.strokeStyle = 'red'
ctx.beginPath()
//arc(圓心x軸,圓心y軸,半徑機關像素,起始角度弧度制從x軸正方向開始,結束角度弧度制,true表示逆時針繪制)
ctx.arc(canvas.width / 2, canvas.height / 2,50, 0, 2*3.14926,true)
ctx.stroke()
}).exec()
}
效果
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsISPrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdsATOfd3bkFGazxCMx8VesATMfhHLlN3XnxCMwEzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5yM5YzN3UWN2gTMzImY1U2NxYzXzQjMwcTMxMzLcBTMxIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjL1M3Lc9CX6MHc0RHaiojIsJye.png)
繪制藝術字:
//繪制文字
drawText() {
// 通過 SelectorQuery 擷取 Canvas 節點
wx.createSelectorQuery().select('#canvas').node(function (res) {
console.log(res.node) // 節點對應的 Canvas 執行個體。
const canvas = res.node
const ctx = canvas.getContext('2d')
ctx.font = "50px sans-serif"
//ctx.fillText("Hello World", 10, 100);
ctx.strokeText("Hello World", 10, 100)
}).exec()
},
效果:
删除指定文字
//繪制文字删除線
drawTextDelete() {
// 通過 SelectorQuery 擷取 Canvas 節點
wx.createSelectorQuery().select('#canvas').node(function (res) {
console.log(res.node) // 節點對應的 Canvas 執行個體。
const canvas = res.node
const ctx = canvas.getContext('2d')
ctx.font = "50px sans-serif"
ctx.fillText("Hello World", 10, 100);
//ctx.globalCompositeOperation = "source-over"; //全局合成操作
ctx.fillStyle = "red";
ctx.fillRect(15, 80, 85, 10);
//ctx.globalCompositeOperation = "source-over"; //全局合成操作
ctx.fillStyle = "red";
ctx.fillRect(160, 80, 30, 10);
}).exec()
},