移动端电子签名,签名内容移动缩放,生成合同图片(uniapp)

529 阅读1分钟

昨天在技术群里看到有人在问电子签名的需求,通过uniapp开发的app,需要实现的签名、签名图片的缩放、拖动、并且和合同一起生成图片。于是利用空闲时间来写了写这个功能。

1、电子签名

电子签名目前已经有很多现成的插件,所以我这里直接选择了一个,有需要的可以看下ext.dcloud.net.cn/plugin?id=4…

代码如下:

HTML:

<view class="content">
		<view style="width: 750rpx ;height: 400px;">
			<l-signature disableScroll backgroundColor="#fff" ref="signatureRef" :penColor="penColor" :penSize="penSize"
				:openSmooth="openSmooth"></l-signature>
		</view>
			<view style="display: flex;">
			<button @click="onClick('clear')">清空</button>
			<button @click="onClick('undo')">撤消</button>
			<button @click="onClick('save')">保存</button>
			<button @click="onClick('openSmooth')">压感{{openSmooth?'开':'关'}}</button>
		</view>
	</view>

JS:

onClick(type) {
				if (type == 'openSmooth') {
					this.openSmooth = !this.openSmooth
					return
				}
				if (type == 'save') {
					this.$refs.signatureRef.canvasToTempFilePath({
						success: (res) => {
							// 是否为空画板 无签名
							console.log(res.isEmpty)
							// 生成图片的临时路径
							// app | H5 | 微信小程序 生成的是base64
							this.url = res.tempFilePath
							// console.log(res.tempFilePath)
							uni.setStorageSync('url',res.tempFilePath)
							uni.navigateTo({
								url:'/pages/result/result'
							})
						}
					})
					return
				}
				if (this.$refs.signatureRef)
					this.$refs.signatureRef[type]()
			}

效果如下: 在这里插入图片描述

2、电子签名图片的拖动缩放

在第一步完成之后,我们可以拿到一个base64格式的图片,在有些需求中签名显示的位置可能是不固定的,需要手动拖动调整,当然一般不会这么做。

拖动缩放我这里直接使用了uniapp自带的movable-area 和 movable-view组件,具体使用方式参见官方文档。

在这里插入图片描述 拖动代码如下:

			<movable-area class="max">
				<movable-view class="quyu" direction="all">
					<image :src="url" mode=""></image>
				</movable-view>
			</movable-area>

3、合同图片的生成

这一步主要使用了html2canvas和uniapp中的renderjs。 html2canvas非常牛逼的一款插件,具体使用方式参见官方文档 html2canvas.hertzen.com/

renderjs是一个运行在视图层的js。它比WXS更加强大。它只支持app-vue和web。

renderjs的主要作用有2个: 1、大幅降低逻辑层和视图层的通讯损耗,提供高性能视图交互能力 2、在视图层操作dom,运行 for web 的 js库

我们在这里主要用到的是它的第二个作用,操作DOM。因为html2canvas是需要根据dom来生成图片的。

主要代码如下:

<script lang="renderjs" module="canvasImage">
	import html2canvas from 'html2canvas'
	export default {
		methods: {
			// 生成图片需要调用的方法
			generateImage(e, ownerFun) {
				ownerFun.callMethod('_showLoading', '正在生成图片')
				setTimeout(() => {
					const dom = document.getElementById('pagePoster') 
					html2canvas(dom, {
						width: dom.clientWidth, 
						height: dom.clientHeight,
						scrollY: 0, // html2canvas默认绘制视图内的页面,需要把scrollY,scrollX设置为0
						scrollX: 0,
						useCORS: true, //支持跨域
						// scale: 2,
					}).then((canvas) => {
						console.log('啊啊啊',canvas)
						// html2canvas 生成成功的图片链接需要转成 base64位的url
						ownerFun.callMethod('receiveRenderData', canvas.toDataURL('image/png'))
					}).catch(err => {
						ownerFun.callMethod('_errAlert', `【生成图片失败,请重试】${err}`)
					})
				}, 300)
			}
		}
	}
</script>

最终效果如下图所示: 在这里插入图片描述 到此结束!