微信小程序canvas画布自由绘制/画笔功能实现

.wxml

<canvas class="canvas" type="2d" id="myCanvas" bindtouchstart="get_edit_position" bindtouchmove="brush"/>

定义canvas元素,需要设置type="2d",后续在js可通过Canvas.getContext('2d') 接口可以获取 CanvasRenderingContext2D对象,用以在画布绘制图形。

bindtouchstart="get_edit_position":用户触摸画布时,获取并更新触摸位置,见以下js部分

 bindtouchmove="brush":用户划动画布时,进行自由绘制,见以下js部分

.wxss

定义canvas显示样式,包含宽度、高度、背景色等,也可自定义其他显示样式。 

.canvas{background-color: white;height: 65vh;width: 100%;margin-top: 5px;margin-bottom: 5px;  
}

.js

获取画布对象:

将获取的canvas和canvas 2d对象通过this.setData设置为全部变量,后续在其他函数可直接调用。 

data:{edit_brush:{},
},
onReady() {const query = wx.createSelectorQuery()query.select('#myCanvas').fields({ node: true, size: true }).exec((res) => {const canvas = res[0].nodeconst ctx = canvas.getContext('2d')canvas.width = res[0].width * dprcanvas.height = res[0].height * dprthis.setData({canvas: canvasctx: ctx})})
},

 获取触摸位置:

监听用户触摸画布开始事件,定义自由绘制开始位置

//触摸开始更新初始位置
get_edit_position(e){var x = e.touches[0].x*this.data.pixelRatiovar y = e.touches[0].y*this.data.pixelRatiothis.setData({"edit_brush.x0":x,"edit_brush.y0":y})
},

自由绘制:

监听用户划动画布事件,不断更新绘制位置进行自由绘制。

//滑动开始自由绘制
brush(e){var x = e.touches[0].x*this.data.pixelRatiovar y = e.touches[0].y*this.data.pixelRatiovar x0 = this.data.edit_brush.x0var y0 = this.data.edit_brush.y0var ctx = this.data.ctx //获取的CanvasRenderingContext2D对象ctx.beginPath()ctx.moveTo(x0,y0)ctx.lineTo(x,y)ctx.closePath()ctx.stroke()this.setData({'edit_brush.x0':x,'edit_brush.y0':y})}

更多内容欢迎关注博主。