<template>
	<view class="center">
		<canvas class="canvas" canvas-id="mycanvas" @touchstart.stop="touchstart" @touchmove.stop="touchmove" @touchend.stop="touchend">
								<text class="txt-font" v-if="showtext">请在此处书写签名</text>
							</canvas>
		<view class="btn flex">
			<view class="button" @click.stop="clear"><text>重写</text></view>
			<view class="button" @click.stop="submit"><text>确认</text></view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				showtext: true,
				ctx: '',//绘画图像
				points: [], //路径点集合
				signature: ''
			}
		},
		onShow() {
			this.ctx = uni.createCanvasContext("mycanvas",this);
			//设置画笔样式
			this.ctx.lineWidth = 4;
			this.ctx.lineCap = "round"
			this.ctx.lineJoin = "round"
		},
		methods: {
			//触摸开始，获取到起点
			touchstart: function(e) {
				this.showtext = false;
				let startX = e.changedTouches[0].x;
				let startY = e.changedTouches[0].y;
				let startPoint = {X:startX,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 = [];
			},
			//绘制笔迹
			//	1.为保证笔迹实时显示，必须在移动的同时绘制笔迹
			//	2.为保证笔迹连续，每次从路径集合中区两个点作为起点（moveTo）和终点(lineTo)
			//	3.将上一次的终点作为下一次绘制的起点（即清除第一个点）
			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 obj = this;
				uni.getSystemInfo({
					success: function(res) {
						let canvasw = res.windowWidth;
						let canvash = res.windowHeight;
						obj.ctx.clearRect(0, 0, canvasw, canvash);
						obj.ctx.draw(true);
					}
				})
			},
			submit(){
				let obj = this;
				uni.canvasToTempFilePath({
					canvasId: 'mycanvas',
					success: function(res) {
						
						console.log(res,'------');
						uni.setStorageSync('mycanvas',res.tempFilePath);
						uni.navigateTo({
							url: '/pages/contract/Qrcontract'
						})
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	page{
		height: 100%;
	}
	.canvas {
		text-align: center;
		line-height: 1000rpx;
		width: 100%;
		height: 1000rpx;
	}
	.btn {
		position: absolute;
		left: 0;
		right: 0;
		width: 100%;
		justify-content: space-between;
		padding: 53rpx;
		margin-bottom: 0;
		.button {
			width: 255rpx;
			height: 74rpx;
			border: 1rpx solid #FE4242;
			background: #FFFFFF;
			border-radius: 37rpx;
			line-height: 74rpx;
			text-align: center;
			text {
				height: 100%;
				font-size: 36rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FF0000;
			}
		}
	}
</style>
