uni-app实现手写签名
<template>
<view class="signature">
<canvas class="signature-canvas" canvas-id="mycanvas" @touchstart="touchstart" @touchmove="touchmove"
@touchend="touchend"></canvas>
<view class="signature-button">
<button type="warn" @click="clear">重写</button>
<button type="primary" @click="finish">保存</button>
</view>
</view>
</template>
<script>
export default {
data() {
return {
ctx: '',
points: [],
signature: '',
}
},
onLoad() {
this.createCanvas()
},
methods: {
createCanvas: function() {
this.ctx = uni.createCanvasContext("mycanvas", this);
this.ctx.setStrokeStyle('red')
this.ctx.lineWidth = 4;
this.ctx.lineCap = "round"
this.ctx.lineJoin = "round"
},
touchstart: function(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: function(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: function() {
this.points = [];
},
draw: function() {
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: function() {
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: function() {
let that = this;
uni.canvasToTempFilePath({
canvasId: 'mycanvas',
success: function(res) {
console.log(res)
}
})
},
}
}
</script>
<style lang="scss">
.signature {
padding: 0 10px;
&-canvas {
width: 100%;
height: 360px;
box-sizing: border-box;
border: 1px solid lightgrey;
}
&-button {
width: 100%;
margin-top: 10px;
display: flex;
button {
flex: 1;
border-radius: 0 !important;
}
}
}
</style>