uni小程序通过canvas绘制签名

<template>
	<view>
		<canvas class="mycanvas" canvas-id="mycanvas" @touchstart="touchstart" @touchmove="touchmove"
			@touchend="touchend"></canvas>
		<view class="footer">
			<view class="left" @click="finish">完成</view>
			<view class="right" @click="clear">清除</view>
		</view>
		<image :src="'data:image/png;base64'+img" mode=""></image>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				ctx: '',
				points: [],
				img: ''
			}
		},
		created() {
			this.ctx = uni.createCanvasContext('mycanvas', this)
			this.ctx.lineWidth = 4
			this.ctx.lineCap = 'round'
			this.ctx.lineJoin = 'round'
		},
		methods: {
			touchstart(e) {
				const x = e.changedTouches[0].x
				const y = e.changedTouches[0].y
				this.points.push({
					x,
					y
				})
				// 开启新路径
				this.ctx.beginPath();
			},
			touchmove(e) {
				const x = e.changedTouches[0].x
				const y = e.changedTouches[0].y
				this.points.push({
					x,
					y
				})
				if (this.points.length >= 2) {
					this.draw()
				}
			},
			touchend() {
				this.points = []
			},
			draw() {
				const p1 = this.points[0]
				const p2 = this.points[1]
				this.points.shift()
				this.ctx.moveTo(p1.x, p1.y)
				this.ctx.lineTo(p2.x, p2.y)
				this.ctx.stroke()
				this.ctx.draw(true)
			},
			clear() {
				const that = this
				uni.getSystemInfo({
					success(e) {
						const {
							screenWidth,
							screenHeight
						} = e
						that.ctx.clearRect(0, 0, screenWidth, screenHeight);
						that.ctx.draw(true);
					}
				})
			},
			finish: function() {
				var that = this
				//生成图片
				uni.canvasToTempFilePath({
					canvasId: 'mycanvas',
					//设置输出图片的宽高
					// destWidth:150, 
					// destHeight:150,
					// fileType:'jpg',
					// quality: 1.0,
					success: function(res) {
						uni.uploadFile({
							filePath: res.tempFilePath,
							name: 'file',
							url: 'http://zyck.top:6220/api/admin/file/Upload',
							success(resImg) {
								uni.showToast({
									title: '上传成功',
									icon: 'none',
									duration: 2000
								})
							},
							fail(resImg) {
								wx.showToast({
									title: '上传失败',
									icon: 'none',
									duration: 2000
								})
							}
						})

						that.img = res.tempFilePath
					},
					fail: function() {
						wx.showModal({
							title: '提示',
							content: 'canvas生成图片失败。微信当前版本不支持,请更新到最新版本!',
							showCancel: false
						});
					},
					complete: function() {}
				})
			},

		}
	}
</script>

<style>
	.mycanvas {
		width: 100%;
		height: 50vh;
		background-color: #ECECEC;
	}

	.footer {
		font-size: 16px;
		height: 150upx;
		display: flex;
		justify-content: space-around;
		align-items: center;
	}

	.left,
	.right {
		line-height: 100upx;
		height: 100upx;
		width: 250upx;
		text-align: center;
		font-weight: bold;
		color: white;
		border-radius: 5upx;
	}

	.left {
		background: #007AFF;
	}

	.right {
		background: orange;
	}

</style>

  

posted @ 2021-11-22 17:31  朱依漾  阅读(122)  评论(0编辑  收藏  举报