對(duì)于手寫簽名組件組件晚上有很多種寫法,我選擇了一種進(jìn)行了wepy的框架的改造。如果使用wepy框架做手寫簽名的話可以直接復(fù)制下面的代碼。
這里需要提醒的是:安卓手機(jī)和蘋果手機(jī)有適配性的問題,蘋果手機(jī)在簽名的以后手機(jī)將無法進(jìn)行文檔的上下左右的滑動(dòng),而安卓手機(jī)沒有影響。解決這個(gè)問題的方法是給canvas給disable-scroll屬性綁定一個(gè)變量 disable-scroll="true" 當(dāng)進(jìn)行滑動(dòng)的時(shí)候講disable-scroll屬性設(shè)置成true,滑動(dòng)完成時(shí)將屬性還原為false.
-
<template>
<view class='content'>
<canvas class='firstCanvas' canvas-id="firstCanvas" bindtouchmove='move' bindtouchstart='start' bindtouchend='end' bindtouchcancel='cancel' bindlongtap='tap' disable-scroll='true' binderror='error'>
</canvas>
<button bindtap='clearClick'>清除</button>
<button bindtap='saveClick'>保存圖片</button>
<image id='signatureImg' src='{{signImage}}'></image>
</view>
</template>
<script>
import wepy from 'wepy';
var content = null;
var touchs = [];
var canvasw = 0;
var canvash = 0;
export default class Index extends wepy.page {
config = {};
components = {};
data = {
signImage: '',
};
events = {};
methods = {
start: function(event) {
// console.log("觸摸開始" + event.changedTouches[0].x)
// console.log("觸摸開始" + event.changedTouches[0].y)
//獲取觸摸開始的 x,y
let point = {
x: event.changedTouches[0].x,
y: event.changedTouches[0].y
}
touchs.push(point)
},
// 畫布的觸摸移動(dòng)手勢(shì)響應(yīng)
move: function(e) {
let point = {
x: e.touches[0].x,
y: e.touches[0].y
}
touchs.push(point)
if (touchs.length >= 2) {
this.draw(touchs)
}
},
// 畫布的觸摸取消響應(yīng)
cancel: function(e) {
console.log("觸摸取消" + e)
},
// 畫布的長(zhǎng)按手勢(shì)響應(yīng)
tap: function(e) {
console.log("長(zhǎng)按手勢(shì)" + e)
},
error: function(e) {
console.log("畫布觸摸錯(cuò)誤" + e)
},
// 畫布的觸摸移動(dòng)結(jié)束手勢(shì)響應(yīng)
end: function(e) {
console.log("觸摸結(jié)束" + e)
//清空軌跡數(shù)組
for (let i = 0; i < touchs.length; i++) {
touchs.pop()
}
},
};
async onShow() {}
async onLoad(options) {
//獲得Canvas的上下文
content = wx.createCanvasContext('firstCanvas')
//設(shè)置線的顏色
content.setStrokeStyle("#00ff00")
//設(shè)置線的寬度
content.setLineWidth(5)
//設(shè)置線兩端端點(diǎn)樣式更加圓潤(rùn)
content.setLineCap('round')
//設(shè)置兩條線連接處更加圓潤(rùn)
content.setLineJoin('round')
}
draw(touchs) {
let point1 = touchs[0]
let point2 = touchs[1]
touchs.shift()
content.moveTo(point1.x, point1.y)
content.lineTo(point2.x, point2.y)
content.stroke()
content.draw(true)
}
clearClick() {
//清除畫布
content.clearRect(0, 0, canvasw, canvash)
content.draw(true)
}
saveClick() {
var that = this
wx.canvasToTempFilePath({
canvasId: 'firstCanvas',
success: function(res) {
//打印圖片路徑
console.log(res.tempFilePath)
//設(shè)置保存的圖片
that.setData({
signImage: res.tempFilePath
})
}
})
}
}
</script>
<style>
.content {
width: 100%;
height: 500px;
background-color: red;
}
.firstCanvas {
background-color: blue;
width: 100%;
height: 200px;
}
image {
width: 100%;
height: 200px;
background-color: orange;
}
</style>
|
|