<template>
	<view class="sign">
		<view class="paper">
			<canvas class="handWriting" disable-scroll="true" @touchstart="touchstart1" @touchmove="touchmove1"
				canvas-id="handWriting1">
			</canvas>
		</view>
		<view class="btns">
			<view class="btn1" @click="reSign1">清除</view>
			<view class="btn2" @click="sign1ok">生成并返回</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import {
		reactive
	} from "vue";
	import {
		onLoad
	} from "@dcloudio/uni-app";
	const state = reactive({
		context1: null,
		hasDraw: false, //默认没有画
		src: null
	})
	onLoad((option) => {
		setTimeout(() => {
			let context1 = uni.createCanvasContext('handWriting1');
			context1.setStrokeStyle("#000000")
			context1.setLineWidth(3);
			state.context1 = context1;
		})
	})

	function touchstart1(e) {
		let context1 = state.context1;
		context1.moveTo(e.touches[0].x, e.touches[0].y);
		state.context1 = context1;
		state.hasDraw = true;
	}

	function touchmove1(e) {
		var x = e.touches[0].x;
		var y = e.touches[0].y;
		var context1 = state.context1;
		context1.setLineWidth(3);
		context1.lineTo(x, y);
		context1.stroke();
		context1.setLineCap('round');
		context1.draw(true);
		context1.moveTo(x, y);
	}

	function reSign1() {
		let context1 = state.context1;
		context1.draw(); //清空画布
		state.hasDraw = false;
		state.src = null;
	}

	function sign1ok() {
		if (!state.hasDraw) {
			console.log("签字是空白的 没有签字")
			uni.showToast({
				title: "请先签名",
				duration: 2000
			});
		} else {
			var context1 = state.context1;
			//保存签名图片到本地
			context1.draw(true, uni.canvasToTempFilePath({
				canvasId: 'handWriting1',
				success(res) {
					console.log(res);
					state.src = res.tempFilePath
				}
			}))
		}
	}

	function signAgreement(file) {
		console.log(file);
	}
</script>
<style lang="scss" scoped>
	.sign {
		//padding: 30rpx;
	}

	.paper {
		// border: 1px solid #dedede;
		margin: 30rpx 0;
		height: 650rpx
	}

	.btns {
		width: 100%;
		display: flex;
		flex-direction: row;
		justify-content: center;

	}

	.btns .btn1,
	.btns .btn2 {
		width: 200rpx;
		height: 70rpx;
		background: #00B38B;
		color: #ffffff;
		text-align: center;
		line-height: 70rpx;
		border-radius: 8rpx;
	}

	.btn1 {
		margin-right: 70rpx;
	}

	.signTitle {
		text-align: center;
		font-size: 1.2em;
		margin: 10px auto;
	}

	.handWriting {
		width: 100%;
		height: 100%;
	}
</style>
