用戶需在APP
或小程序
使用手寫的方式簽字或簽名vue
(推薦)
index.vue
<!-- canvas -->
<canvas class="mycanvas" canvas-id="mycanvas" @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend"></canvas>
<!-- 底部操做按鈕 -->
<view class="footer">
<view class="left" @click="finish">保存</view>
<view class="right" @click="clear">清除</view>
<view class="close" @click="close">關閉</view>
</view>
<view @click='createCanvas()'>點擊觸發寫字板</view>
複製代碼
上面的canvas
共綁定了3個方法canvas
方法名 | 方法解讀 |
---|---|
@touchstart | 手寫觸摸開始,獲取到起點 |
@touchmove | 手寫觸摸移動,獲取到路徑點 |
@touchend | 手寫觸摸結束 |
export default {
data() {
return {
//繪圖圖像
ctx: '',
//路徑點集合
points: [],
//簽名圖片
SignatureImg: ''
}
}
}
複製代碼
該方法主要是建立了畫布
觸摸開始,獲取到起點
觸摸移動,獲取到路徑點
觸摸結束,將未繪製的點清空防止對後續路徑產生干擾
繪製筆跡
清空畫布
完成繪畫並保存到本地
methods: {
createCanvas() {
//建立繪圖對象
this.ctx = uni.createCanvasContext('mycanvas', this);
//設置畫筆樣式
this.ctx.lineWidth = 4;
this.ctx.lineCap = 'round';
this.ctx.lineJoin = 'round';
},
touchstart(e) {
let startX = e.changedTouches[0].x;
let startY = e.changedTouches[0].y;
let startPoint = { X: startX, Y: startY };
this.points.push(startPoint);
//每次觸摸開始,開啓新的路徑
this.ctx.beginPath();
},
touchmove(e) {
let moveX = e.changedTouches[0].x;
let moveY = e.changedTouches[0].y;
let movePoint = { X: moveX, Y: moveY };
this.points.push(movePoint); //存點
let len = this.points.length;
if (len >= 2) {
this.draw(); //繪製路徑
}
},
touchend() {
this.points = [];
},
draw() {
let point1 = this.points[0];
let point2 = this.points[1];
this.points.shift();
this.ctx.moveTo(point1.X, point1.Y);
this.ctx.lineTo(point2.X, point2.Y);
this.ctx.stroke();
this.ctx.draw(true);
},
clear() {
let that = this;
uni.getSystemInfo({
success: function(res) {
let canvasw = res.windowWidth;
let canvash = res.windowHeight;
that.ctx.clearRect(0, 0, canvasw, canvash);
that.ctx.draw(true);
}
});
},
finish() {
let that = this;
uni.canvasToTempFilePath({
canvasId: 'mycanvas',
success: function(res) {
//這裏的res.tempFilePath就是生成的簽字圖片
console.log(res.tempFilePath);
}
});
}
}
複製代碼
上面finish()
方法獲得的res.tempFilePath
就是生成出來的簽名,可用於作餘下的業務操做小程序