需要背景
某我的项目须要实现在线电子签名性能,其次要性能点如下
- 能够用鼠标在指定区域中电子签名
- 签名区域能够实现自适应大小
- 签名后的后果能够以二进制流的形式上传到服务器,不便电子签章
实现的成果如下
筹备工作
须要提前装置如下的组件
- react-signature-canvas 参考地址
resize-observer-polyfill 参考地址
装置指令npm i -S react-signature-canvasnpm install resize-observer-polyfill --save-dev
自适应性能实现
<div className={styles.div_signature} ref={this.parentRef}> <SignatureCanvas penColor="black" canvasProps={canvasProps} ref={(ref) => { this.canvas = ref; }} /></div>
SignatureCanvas为签名区域,父级div获取到ref,并通过resize-observer-polyfill组件计算其高度。其实现函数如下:
parentRef = (cw) => { // containerWrap if (cw) { const ro = new ResizeObserver((entries, observer) => { // eslint-disable-next-line no-restricted-syntax for (const entry of entries) { const { left, top, width, height } = entry.contentRect; this.setState({ cvWidth: width, }); } }); ro.observe(cw); } };
签名后果上传
在签名组件中应用如下的代码获取签名图片并通过父组件的submitSign提交到父组件
其代码如下:const { submitSign } = this.props; const imgUrl = this.canvas.toDataURL('image/png'); submitSign(imgUrl);
父组件获取到图片后即可通过fetch上传到服务器
const fileObj = dataURLtoFile(signImgURL, 'sign.png'); const formData = new FormData(); formData.append('file', fileObj); formData.append('action', 'UploadVMKImagePath'); fetch(`${uploadUrl}api/files/upload`, { method: 'post', body: formData, }).then(response => response.json()) .then((res) => { console.log(res); });