效果如下:
请结合小程序官方文档进行解读
wxml:
<view> <view>请在下方签字:</view> <canvas id="myCanvas" type="2d" style="border:1px solid #d3d3d3;" bindtouchstart="start" bindtouchmove="move" bindtouchend="end"/> <view> <button bind:tap="clearCan">清除</button> <button type="submit" bind:tap="submitCan">保存</button> <van-image width="100" height="100" model:src="{{canvanImg}}" /> </view> </view>
js:
/** * 页面的初始数据 */ data: { canvas:null, CanvasCote:null, canvanImg:"", }, //触摸开始 start (e) { this.data.CanvasCote.beginPath() this.data.CanvasCote.moveTo(e.touches[0].x,e.touches[0].y) }, //触摸移动 move (e) { this.data.CanvasCote.lineTo(e.touches[0].x, e.touches[0].y) this.data.CanvasCote.stroke()//将上下文绘制到canvas中 }, //触摸结束 end (e) { this.data.CanvasCote.closePath() }, //清除画布内容 clearCan(){ this.data.CanvasCote.clearRect(0, 0,this.data.canvas.width, this.data.canvas.height) this.setData({ canvanImg:"" }) }, //点击保存生成图片 submitCan(){ this.setData({ canvanImg:this.data.canvas.toDataURL("image/png") }) console.log(this.data.canvas.toDataURL("image/png")) }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { let that = this; //如果在 exec 中获取不到res,这里就写 wx.createSelectorQuery().in(this) const query = wx.createSelectorQuery() query.select('#myCanvas').node().exec((res) => { that.setData({ canvas: res[0].node, CanvasCote: res[0].node.getContext('2d') }) let ctx = that.data.CanvasCote; ctx.fillStyle = "#fff" ctx.fillRect(0, 0, that.data.canvas.width, that.data.canvas.height); ctx.strokeStyle='black' ctx.lineCap = 'round'; // 线条末端添加圆形线帽,减少线条的生硬感 ctx.lineJoin = 'round'; // 线条交汇时为原型边角 // 利用阴影,消除锯齿 ctx.shadowBlur = 1; ctx.shadowColor = '#000'; }) },标签:canvas,res,ctx,touches,签字,2D,CanvasCote,data From: https://www.cnblogs.com/smile-fanyin/p/16730780.html