新版 2D微信小程序 一个手写签名组件,直接复制粘贴即可使用
小程序模板
<view class="box">
<view class="canvasbox" style="width:calc( {{pm_width}}rpx - 28rpx);height: calc( {{pm_height}}rpx - 100rpx );">
<canvas type="2d" id="myCanvas"bindtouchstart="touchstart1" bindtouchmove="touchmove1"
style="width:calc( {{pm_width}}rpx - 28rpx);height: calc( {{pm_height}}rpx - 100rpx );"></canvas>
</view>
<view class="signBtn">
<text bindtap="sign1ok" class="sign1ok">完成签字</text>
<text bindtap="reSign1" class="reSign1">重新签字</text>
</view>
</view>
小程序样式css
.box {
display: block;
}
.canvasbox {
display: block;
border: 1px solid #f00;
margin: auto;
margin-bottom: 10rpx;
margin-top: 10rpx;
}
.signBtn {
width: 100%;
display: flex;
justify-content: center;
height: 80rpx;
align-items: center;
}
.sign1ok {
height: 40rpx;
line-height: 40rpx;
background-color: #f00;
display: block;
border-radius: 100rpx;
padding-left: 20rpx;
padding-right: 20rpx;
color: #fff;
}
.reSign1 {
height: 40rpx;
line-height: 40rpx;
background-color: #00a1e9;
display: block;
border-radius: 100rpx;
padding-left: 20rpx;
padding-right: 20rpx;
color: #fff;
margin-left: 50rpx;
}
小程序样式单页面 json
{
"usingComponents": {},
"pageOrientation": "landscape",
"disableScroll" : true
}
小程序样式javascript
Page({
data: {
context:'',
canvasbox:'',
hasDraw:false,
pm_width:'',
pm_height:'',
},
onLoad(options) {
wx.showToast({
title: '请在红框内签名',
icon: 'none',
duration: 2000
})
wx.getSystemInfo({
success:(res)=> {
var kuan = (res.windowWidth * (750 / res.windowWidth));
var gao = (res.windowHeight * (750 / res.windowWidth));
this.setData({
pm_width: kuan,
pm_height:gao,
})
}
})
},
onReady() {
const query = wx.createSelectorQuery()
query.select('#myCanvas')
.fields({ node: true, size: true })
.exec((res) => {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
const dpr = wx.getSystemInfoSync().pixelRatio
canvas.width = res[0].width * dpr
canvas.height = res[0].height * dpr
ctx.scale(dpr, dpr)
this.setData({
context: ctx,
canvasbox:canvas,
})
})},
touchstart1: function(e) {
var context1 = this.data.context;
context1.moveTo(e.touches[0].x, e.touches[0].y);
this.setData({
context: context1,
hasDraw : true,
});
},
touchmove1: function(e) {
var x = e.touches[0].x;
var y = e.touches[0].y;
this.data.context.lineWidth='4';
this.data.context.lineTo(x, y);
this.data.context.stroke();
this.data.context.setLineCap='round';
this.data.context.beginPath();
this.data.context.moveTo(x, y);
},
reSign1: function() {
var that = this;
var context1 = that.data.context;
context1.draw=true;
context1.beginPath();
context1.clearRect(0, 0, that.data.pm_width, that.data.pm_height);
that.setData({
hasDraw: false,
src: null
});
},
sign1ok: function () {
var that = this;
if(!that.data.hasDraw){
wx.showToast({
title: '您还没有签字',
icon: 'none',
duration: 2000
})
} else{
var context1 = that.data.context;
wx.canvasToTempFilePath({
canvas:that.data.canvasbox,
fileType: "png",
quality: 1,
success: (res) => {
console.log(res.tempFilePath)
}
})
}
},
})