用的是canvas 最后转为base64格式的图片文件
Page({
data: {
canvas: null,
ctx: null,
alreadyDraw: false,
src: null,
width: 0,
height: 0
},
onReady() {
const query = wx.createSelectorQuery()
query.select('#myCanvas')
.fields({ node: true, size: true })
.exec((res) => {
console.log(res)
// Canvas 对象
const canvas = res[0].node
// 渲染上下文
const ctx = canvas.getContext('2d')
console.log(canvas, ctx)
// Canvas 画布的实际绘制宽高
const width = res[0].width
const height = res[0].height
// 初始化画布大小
const dpr = wx.getSystemInfoSync().pixelRatio
canvas.width = width * dpr
canvas.height = height * dpr
ctx.scale(dpr, dpr)
ctx.lineWidth = 3
ctx.lineCap = 'round'
this.setData({
canvas,
ctx,
width,
height
})
})
},
/** 开始触摸 */
touchStart(e) {
console.log(e)
let ctx = this.data.ctx
ctx.moveTo(e.touches[0].x, e.touches[0].y);
this.setData({
ctx,
});
},
/** 移动 */
touchMove(e) {
var ctx = this.data.ctx;
const x = e.touches[0].x
const y = e.touches[0].y
ctx.lineTo(x, y);
ctx.stroke();
ctx.moveTo(x, y);
if (!this.data.alreadyDraw) {
this.setData({
alreadyDraw: true,
});
}
},
/** 重新签名 */
reSign() {
const { ctx, width, height } = this.data
ctx.clearRect(0, 0, width, height)
this.setData({
ctx,
src: null,
alreadyDraw: false,
})
},
/** 完成签名 */
signOk() {
if (!this.data.alreadyDraw) {
wx.showToast({
title: '请先签字',
icon: 'none'
})
} else {
var canvas = this.data.canvas;
const img = canvas.toDataURL()
// console.log(img)
this.setData({
src: img
})
}
},
})