1.paint.wxml
<canvas id="canvas" type="2d" bindtouchstart="paints" bindtouchmove="paintm" style="width:{{width}}px;height:{{height}}px;border:1px solid green;"></canvas>
2.paint.js
data: {
ctx:'',
width:350,
height:500
},
onLoad(options) {
this.canvasinit()
},
方法:canvasinit()、paints()、paintm()
canvasinit:function(){
wx.createSelectorQuery() //此方法等于获取页面所有节点
.select('#canvas') //类似原生JS的选择器,这里根据id
.fields({ node: true, size: true })//获取到的节点属性配置,node是否返回实例,size是否返回尺寸大小尺寸
.exec((res)=>{ //获取之后的回调
const canvas = res[0].node// Canvas 对象
const ctx = canvas.getContext('2d')// 渲染上下文
const renderW = res[0].width
const renderH = res[0].height
const dpr = wx.getWindowInfo().pixelRatio
canvas.width = renderW * dpr
canvas.height = renderH * dpr
ctx.scale(dpr,dpr)
this.setData({
ctx:ctx,
})
})
},
paints:function(e){
let x = e.touches[0].x
let y = e.touches[0].y
const ctx = this.data.ctx
ctx.lineCap = "round"
ctx.lineJoin = "round"
ctx.strokeStyle = "#000000"
ctx.lineWidth = 5
ctx.moveTo(x,y)
},
paintm:function(e){
let x = e.touches[0].x
let y = e.touches[0].y
const ctx = this.data.ctx
ctx.lineTo(x,y)
ctx.stroke()
},
出现错误:Do not have paintm handler in component....或者Do not have pints handler in component....
请检查基础库:基础库为2.21.4或以上