start
- 最近遇到需求,说是要在前端页面,做一个电子签名的功能。
- 以前番茄玩过不少canvas的demo,这玩意我第一反应就是canvas。
- 简单记录一下这个功能。
github
-
自己造轮子有点麻烦,不如去github找一下。有一个关于电子签名200个star的库:
vue-esign
,支持vue2,vue3。查看了一下demo符合我们的要求,就它了。
-
官网地址
https://github.com/JaimeCheng/vue-esign
- 安装依赖
npm install vue-esign --save
基本使用
<template>
<div id="app">
<div class="box">
<vue-esign
ref="esign"
:width="800"
:height="400"
:isCrop="isCrop"
:lineWidth="lineWidth"
:lineColor="lineColor"
:bgColor.sync="bgColor"
/>
</div>
<div class="button">
<button @click="handleReset">清空画板</button>
<button @click="handleGenerate">生成图片</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
lineWidth: 6,
lineColor: "#000000",
bgColor: "",
resultImg: "",
isCrop: false,
};
},
methods: {
handleReset() {
this.$refs.esign.reset();
},
handleGenerate() {
this.$refs.esign
.generate()
.then((res) => {
this.resultImg = res;
// 默认生成的是base64形式的图片,
const a = document.createElement("a");
a.href = res;
a.download = "签名.png";
a.click();
a.remove()
})
.catch((err) => {
alert(err); // 画布没有签字时会执行这里 'Not Signned'
});
},
},
};
</script>
<style>
body,
#app {
width: 100%;
height: 100%;
background-color: #eee;
position: relative;
}
.box {
margin: 40px auto;
width: 800px;
height: 400px;
background-color: #fff;
overflow: hidden;
}
.button {
text-align: center;
}
button {
padding: 10px 25px;
background: #1889fa;
color: white;
border: 0;
border-radius: 5px;
cursor: pointer;
}
</style>
其他
来都来了,顺便看下的它的源码
- 一个是用来注册的index.js文件
- 一个就是vue的组件,基本就是canvas加鼠标监听事件完成的一个小功能。这里看到它是支持移动端的touch的。没啥难度,就到这了。
总结
- 全程下来,算上创建vue项目,以及安装依赖,5分钟搞定。
- 这个库还可以,挺实用的功能。