// component/sign/sign.js Component({ options: { addGlobalClass: true }, /** * 组件的属性列表 */ properties: { show: { type: Boolean, value: false }, title: { type: String, value: "手写签名" }, yes: { type: String, value: "确定" }, no: { type: String, value: "取消" }, showBtn: { type: Boolean, value: true } }, /** * 组件的初始数据 */ data: { }, //决定是否绘制的最小像素距离 TOUCH_TOLERANCE: 4, // pageLifetimes: { // show: function () { // this.init() // } // }, onReady: function () { this.init() }, /** * 组件的方法列表 */ methods: { init: function () { wx.createSelectorQuery().in(this) .select('.sign-canvas') .fields({ node: true, size: true }) .exec((res) => { //Canvas 对象 const canvas = res[0].node //渲染上下文 const ctx = canvas.getContext('2d') //Canvas画布的实际绘制高度 this.width = res[0].width this.height = res[0].height //初始化画布大小 const dpr = wx.getWindowInfo().pixelRatio canvas.width = this.width * dpr canvas.height = this.height * dpr ctx.scale(dpr, dpr) this.canvas = canvas this.ctx = ctx }) }, touchStart(e) { if (this.canvas && e.touches.length > 0) { var t = e.touches[0]; this.ctx.moveTo(t.x, t.y) this.tempX = t.x this.tempY = t.y } }, touchMove(e) { if (this.canvas && e.touches.length > 0) { var t = e.touches[0]; var dx = Math.abs(t.x - this.tempX) var dy = Math.abs(t.y - this.tempY) if (dx >= this.TOUCH_TOLERANCE || dy >= this.TOUCH_TOLERANCE) { this.ctx.lineTo(t.x, t.y) this.ctx.stroke() this.tempX = t.x this.tempY = t.y } } }, touchEnd(e) { if (this.canvas && e.touches.length > 0) { var t = e.touches[0]; this.ctx.lineTo(t.x, t.y) this.ctx.stroke() } }, onClose(e) { this.setData({ show: false }) this.ctx.clearRect(0, 0, this.width, this.height) this.triggerEvent('close') }, onCancel(e) { this.ctx.clearRect(0, 0, this.width, this.height) }, onConfirm(e) { this.ctx.closePath() wx.canvasToTempFilePath({ canvas: this.canvas, success(res) { this.triggerEvent('confirm', { path: res }) }, fail(res) { }, complete(res) { } }) } } })