微信小程序使用Canvas实现签字绘制功能
1、效果图
2、代码仓库
https://gitee.com/synctimes/canvas-sign/tree/master
3、部分代码演示
Page({
data: {
context1: null,
hasDraw: false, //默认没有画
src: null
},
onLoad: function () {
var self = this;
var context1 = wx.createCanvasContext('handWriting1');
context1.setStrokeStyle("#000000")
context1.setLineWidth(3);
this.setData({
context1: context1,
})
},
touchstart1: function (e) {
var context1 = this.data.context1;
context1.moveTo(e.touches[0].x, e.touches[0].y);
this.setData({
context1: context1,
hasDraw: true, //要签字了
});
},
touchmove1: function (e) {
var x = e.touches[0].x;
var y = e.touches[0].y;
var context1 = this.data.context1;
context1.setLineWidth(3);
context1.lineTo(x, y);
context1.stroke();
context1.setLineCap('round');
context1.draw(true);
context1.moveTo(x, y);
},
reSign1: function () { //重新画
var self = this;
var context1 = self.data.context1;
context1.draw(); //清空画布
self.setData({
hasDraw: false, //没有画
src: null
});
self.ajaxLoading = false;
},
sign1ok: function () {
var self = this;
if (!self.data.hasDraw) {
console.log("签字是空白的 没有签字")
return
}
var context1 = self.data.context1;
context1.draw(true, wx.canvasToTempFilePath({
canvasId: 'handWriting1',
success(res) {
console.log(res.tempFilePath) //得到了图片下面自己写上传吧
self.setData({
src: res.tempFilePath
})
const fs = wx.getFileSystemManager();
fs.getFileInfo({
filePath: res.tempFilePath,
success(result) {
console.log("getFileInfo result=>", result)
res.size = result.size;
},
fail(err) {
}
})
}
}))
},
});
<view class="g-doc">
<view class="g-bd">
<view class="paper">
<canvas class="handWriting" disable-scroll="true" bindtouchstart="touchstart1" bindtouchmove="touchmove1" canvas-id="handWriting1">
</canvas>
</view>
</view>
<view class="g-ft">
<view class="weui-flex">
<view class="weui-flex__item" bindtap="reSign1">
<view class="f-ins2">
重新签字
</view>
</view>
<view class="weui-flex__item" bindtap="sign1ok">
<view class="f-ins1">
提交
</view>
</view>
</view>
<view class="iphonex-env-constant"></view>
</view>
</view>
4、相关参考文献
https://developers.weixin.qq.com/miniprogram/dev/component/canvas.html
https://juejin.cn/post/6991670574200127495
5、使用问题描述
签字三 在真机安卓手机下,存在无法绘制问题。
签字二,实际使用场景中,因为我是在 列表页-列表详情页-表单页-签字页。存在页面较多层级的状态下,会出现卡顿,iPhone越画往后会感觉卡顿明显。而页面栈只有一层时,则很流畅。
怎么用新版的canvas替代呢,旧版的画多了性能太差了,我在touchmove里面调用这个,前一次的都不保留。
wx.createSelectorQuery().select('#myCanvas1').fields({node: true, size: true })
.exec((res)=>{
canvas = res[0].node
const renderWidth = res[0].width
const renderHeight = res[0].height
ctx = canvas.getContext('2d')
// const dpr = wx.getWindowInfo().pixelRatio
canvas.width = renderWidth * dpr;
canvas.height = renderHeight * dpr;
ctx.scale(dpr, dpr);
ctx.fillRect(this.data.x, this.data.y, 50, 50);
ctx.fillRect(20, 20, 50, 50);
})
},