用uniapp在微信小程序实现画板(电子签名)功能

目录

一、效果展示

二、插件推荐与引入

三、代码具体应用

四、h5端将base64转换为url

一、效果展示

二、插件推荐与引入

手写板、签字板;<zwp-draw-pad /> - DCloud 插件市场

这个在微信小程序引入时内容简单,且涉及的方法很多,可满足撤销、删除、保存、画笔颜色修改等操作。其中保存的图片结果是base64,可借助微信小程序的转换方法将其转换为url临时地址。

三、代码具体应用

	<view class="content">
		<zwp-draw-pad :width="w" :height="h" ref="drawPad" />
		<view class="sa" @click="onCancel()">
			撤销
		</view>
		<view class="sa" @click="onSave()">
			保存
		</view>
		<view class="sa" @click="onClear()">
			清除
		</view>
	</view>
<script>
import { base64src } from "../../utils/base64src.js"; // 后面引用路径为base64src.js文件路径
	export default {
		data() {
			return {
				w: 375,
				h: 375,
			}
		},
		methods: {
			onSave() {
				this.$refs.drawPad.save().then(res => {
					console.log('保存图片的地址', res.tempFilePath)
					base64src( res.tempFilePath, (res) => {
						console.log(res); // 转换后的临时连接路径
					});
				})
			},
			onCancel() {
				this.$refs.drawPad.back()
			},
			onClear() {
				this.$refs.drawPad.init()
				this.$refs.drawPad.clearCache()
			},
		}
	}
</script>

其中通过this.$refs.drawPad.originData.length 是否>0来判断是否在画板上进行了签名

借助工具函数,使用引入即可!

const base64src = (base64data, fun) => {
  const base64 = base64data; //base64格式图片
  const time = new Date().getTime();
  const imgPath = wx.env.USER_DATA_PATH + "/poster" + time + "share" + ".png";
  //如果图片字符串不含要清空的前缀,可以不执行下行代码.
  const imageData = base64.replace(/^data:image\/\w+;base64,/, "");
  const file = wx.getFileSystemManager();
  file.writeFileSync(imgPath, imageData, "base64");
  fun(imgPath);
};
export { base64src };

四、h5端将base64转换为url

			base64ImgtoFile (dataurl, filename = 'file') { 
			      const arr = dataurl.split(',')
			      const mime = arr[0].match(/:(.*?);/)[1]
			      const suffix = mime.split('/')[1]
			      const bstr = atob(arr[1])
			      let n = bstr.length
			      const u8arr = new Uint8Array(n)
			      while (n--) { 
			        u8arr[n] = bstr.charCodeAt(n)
			      }
			      return new File([u8arr], `${ filename}.${ suffix}`, { 
			        type: mime
			      })
			    },
let file = this.getBase64ImageUrl(res.tempFilePath) // 得到File对象(res.tempFilePath即为base64形式)
this.imgUrl = window.webkitURL.createObjectURL(file) || window.URL.createObjectURL(file) // imgUrl图片网络路径

扫描二维码关注公众号,回复: 17449678 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_44930306/article/details/134581422