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()
}
效果

繪制藝術字:
//繪制文字
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()
},
效果:

更多知識參考文檔:https://www.runoob.com/w3cnote/html5-canvas-intro.html
