vue-esign和vue-signature-pad
工作中承接h5项目,需要实现手写签名的功能,可以清除和保存手写签名,就调研了两种签名插件链接: vue-esign和vue-signature-pad
vue-esign: https://gitee.com/zhuhj7001/vue-esign
vue-signature-pad: https://github.com/neighborhood999/vue-signature-pad
先来粗略介绍一下两个插件的异同点:
相同点
- 兼容 PC 和 Mobile;
- 同时支持vue2和vue3;
- 画布自适应屏幕大小变化(窗口缩放、屏幕旋转时画布无需重置,自动校正坐标);
- 自定义画布尺寸(导出图尺寸),画笔粗细、颜色,画布背景色
不同点
- vue-signature-pad 因为他带笔压!就类似数位板画画的压感,画笔线条根据使用者的用力大小显示不同粗细,不是固定粗细的,vue-esign不支持此功能;
- vue-signature-pad 的Vue 2 和Vue 3 依赖安装版本不同;vue-esign都版本向下兼容,不需要区分Vue 2 和Vue 3;
- vue-signature-pad支持单步撤回
以上总结,vue-signature-pad的功能更丰富些
选型和使用
因为是vue3项目,同时不需要笔压控制,同时只需要清空和保存,就选择了vue-esign
依赖安装
npm install vue-esign --save
引入vue-esign
// 局部引入
import vueEsign from ‘vue-esign’;
html部分
<nut-popup
v-model:visible="state.showPopup"
:destroy-on-close="false"
closeable
pop-class="sign-form-popup"
position="bottom"
round
>
<div class="form-item-popup-content">
<div class="title">设计师签字</div>
<div class="form-item-popup-operate">
<vue-esign
class="sign-canvas"
ref="esignRef"
style="height: 390px !important;"
:lineWidth="state.lineWidth"
:lineColor="state.lineColor"
v-model:bgColor="state.bgColor"
:isClearBgColor="false"
/>
<div class="btn">
<nut-button type="default" @click="handleReset">清除签字</nut-button>
<nut-button type="primary" @click="handleGenerate">保存</nut-button>
</div>
</div>
</div>
</nut-popup>
js部分
nut-popup为京东风格的轻量级移动端组件库nutui组件弹窗层
// 局部
import vueEsign from 'vue-esign';
// 页面来源
import { inject, nextTick, reactive, ref, watch } from 'vue';
const state = reactive({
showPopup: false,
resultImg: '',
lineWidth: 4,
lineColor: '#000000',
bgColor: '#f5f5f5',
});
// sign是签名弹窗,监听改变width和高是签字区域和显示可视位置对应
watch(
() => state.showPopup,
(val, oldVal) => {
if (val) {
nextTick(()=>{
let canvas = document.querySelector('.sign-canvas');
canvas.height = 390;
canvas.width = window.innerWidth;
})
}
}
);
const esignRef = ref();
function handleReset() {
// 清除
esignRef.value.reset();
}
function handleGenerate() {
esignRef.value
.generate({ format: 'image/jpeg', quality: 2 })
.then(res => {
state.resultImg = res;// base64图片
handleReset();
})
.catch(err => {
// 错误提示信息
alert('请签字');
});
}
<style lang="scss" scoped>
.form-item-popup-operate {
width: 100%;
}
.sign-canvas {
margin-top: 6px;
margin-bottom: 60px;
background-color: #f5f5f5;
canvas {
width: 100%;
height: 390px;
}
}
</style>