uni-app使用canvas实现签名画布 (保存本地) 源码

95 阅读1分钟
<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>