<template>
<view class="box">
<canvas class="firstCanvas" :disable-scroll="true" canvas-id="firstCanvas" @touchstart="touchstart"
@touchmove="touchmove" @touchend="touchend"></canvas>
<view class="operate">
<button class="clear" @click="clear">清除</button>
<button class="preserve" @click="preserve">保存</button>
</view>
</view>
</template>
<script>
export default {
data() {
return {
ctx: null,
points: [],
isEnd: false
}
},
onLoad() {
},
onReady() {
this.ctx = uni.createCanvasContext("firstCanvas", this);
},
methods: {
touchstart(e) {
this.flag = true
let startX = e.changedTouches[0].x;
let startY = e.changedTouches[0].y;
let startPoint = {
X: startX,
Y: startY
};
this.points.push(startPoint);
},
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(e) {
this.points = [];
this.isEnd = true
},
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() {
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);
},
})
},
preserve() {
let that = this
if (!this.isEnd) {
uni.showToast({
title: '请先完成签名',
icon: "none",
duration: 1500,
mask: true
})
return
}
uni.canvasToTempFilePath({
canvasId: 'firstCanvas',
success: function(res) {
console.log(res)
that.$emit('signDone', res.tempFilePath)
let path = res.tempFilePath;
uni.saveImageToPhotosAlbum({
filePath:path,
})
}
})
},
}
}
</script>
<style lang="scss">
.operate {
text-align: center;
button {
width: 80px;
display: inline-block;
margin-left: 10px;
}
}
* {
list-style: none;
box-sizing: border-box;
margin: 0;
padding: 0;
}
canvas {
border: 1px solid #333;
margin: 20px auto;
}
</style>