vue3后管项目电子签名插件之:vue-signature-pad插件

需求:现在有一个后管项目,需要使用到电子签名,想把签名后的文件保存为一个图片,上传到服务器,最后,保存时传给后端一个URL链接。

步骤一:首先,安装
vue-signature-pad

npm install vue-signature-pad --save

yarn add vue-signature-pad

步骤二:在需要的页面引入

import { VueSignaturePad } from 'vue-signature-pad';

我封装了一个子组件:

<template>
  <div>
    <vue-signature-pad ref="signaturePad" class="signature" :options="options" width="780px"></vue-signature-pad>
    <a class="clear_a" @click="clearSignature">清除签名</a>
  </div>
</template>

<script setup>
import { VueSignaturePad } from 'vue-signature-pad';
import { ref, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';
const signaturePad = ref();
const option = ref({
  penColor: '#000000',
  minWidth: 2,
  maxWidth: 2,
});

// 清除签名
const clearSignature = () => {
  // 撤销返回上一步
  // signaturePad.value.undoSignature();

  // 直接清空
  signaturePad.value.clearSignature();
};

// 保存
const updateParent = () => {
  const response = signaturePad.value.saveSignature();
  if (response.isEmpty) {
    return response;
  } else {
    // 转成二进制形式
    const binaryData = convertBase64ToBinary(response.data);
    const blob = new Blob([binaryData], { type: 'image/png' });
    // console.log('+子组件43+', blob)
    return blob;
  }
};

function convertBase64ToBinary(base64Str) {
  // 去除data:image/png;base64,这部分,只保留Base64编码的字符串
  const base64Data = base64Str.split(',')[1];
  // 使用atob函数解码Base64字符串
  const binaryStr = atob(base64Data);
  // 创建一个Uint8Array来保存二进制数据
  const len = binaryStr.length;
  const bytes = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    bytes[i] = binaryStr.charCodeAt(i);
  }
  // 返回Uint8Array对象,或者根据需要进一步处理
  return bytes;
}


// 这样在父组件可以直接通过ref调用该方法
defineExpose({
  updateParent,
});
</script>

<style lang="scss" scoped>
.signature {
  background-color: #e9ecfc;
  border-radius: 5px;
  width: 780px;
  height: 100%;
}
.clear_a {
  cursor: pointer;
  position: absolute;
  right: 15px;
  bottom: 10px;
}
</style>

步骤三:父组件使用

          <el-col :span="18" style="min-width: 450px">
            <el-form-item label="手写签名">
              <!-- 签名版 -->
              <div class="box_signature">
                <signatureBoard ref="signatureRef" class="parent-container"></signatureBoard>
              </div>
            </el-form-item>
          </el-col>

样式

.box_signature {
  min-width: 280px;
  // width: 780px;
  // width: calc(80vw - 50px);
}
.parent-container {
  width: 100%;
  height: 300px;
  padding: 0;
  margin: 0;
}

步骤四:通过ref来触发子组件的保存文件方法

const signatureRef = ref();
signatureRef.value.updateParent()

备注:这里返回的是,已经处理好的二进制文件,可以直接上传给后端接口,原生直接返回的是base64格式编码的文件。

步骤五:查看效果

警告:如果需要进行样式调整时,得格外注意,否则会干扰鼠标进行签名时的位置。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值