react签字功能 react-signature-canvas
.
前几天一个月薪35k的兄弟,给我推了一个人工智能学习网站,看了一段时间挺有意思的。包括语音识别、机器翻译等从基础到实战都有,很详细,分享给大家。大家及时保存,说不定啥时候就没了。
.
效果
插件地址
react-signature-canvas
代码
1、安装 react签字功能 react-signature-canvas
npm install react-signature-canvas
或者使用yarn,都是ok的
2、使用
index.jsx
import React from 'react';
import './sign.less'
import { Button, } from 'antd-mobile'
import { useEffect, useState, useRef, } from "react";
import SignatureCanvas from 'react-signature-canvas';
function SignWrite() {
const sigCanvas = useRef({});
const clearCanvas = () => {
sigCanvas.current.clear();
};
const getCanvasImage = () => {
const base64Img = sigCanvas.current.getTrimmedCanvas().toDataURL("image/png");
console.log(base64Img); // This is the base64 string representation of the signature
};
return (
<div className = 'signContent'>
<div className="writeContent">
<SignatureCanvas
penColor="black"
canvasProps={{ className: "sigCanvas" }}
ref={sigCanvas}
/>
</div>
<div className="btnGroup">
<Button onClick={clearCanvas}>Clear</Button>
<Button onClick={getCanvasImage}>Save</Button>
</div>
</div>
);
}
export default SignWrite;
sign.less
.sigCanvas {
width: 100%;
height: calc(100vh - 158px);
}
In this example, we import SignatureCanvas from the package, create a ref to the canvas element, and add a button that clears the canvas when clicked. We pass penColor and canvasProps as props to the SignatureCanvas component, and then add the reference to sigCanvas.
we have added a new function called getCanvasImage which retrieves the base64 string of the trimmed canvas image. We call this function when the “Save” button is clicked.
You can customize the penColor and canvasProps to fit your needs. For instance, you can change the width and height of the signature canvas to adjust the size of the signature.
判断用户是否签字
react-signature-canvas 提供了一个方法来判断画布是否已经被签字。使用isEmpty()
方法,将返回一个布尔值来指示画布是否为空(没有签字)。
在你的代码中,你可以添加一个条件语句以根据签名的状态显示或隐藏一些内容。下面是一个示例代码:
import React, { useRef } from "react";
import SignatureCanvas from 'react-signature-canvas';
function App() {
const sigCanvas = useRef({});
const clearCanvas = () => {
sigCanvas.current.clear();
};
const getCanvasImage = () => {
const base64Img = sigCanvas.current.getTrimmedCanvas().toDataURL("image/png");
console.log(base64Img);
};
return (
<div>
<SignatureCanvas
penColor='black'
canvasProps={{width: 500, height: 200, className: 'sigCanvas'}}
ref={sigCanvas}
/>
{sigCanvas.current.isEmpty() ? (
<div>Please sign</div>
) : (
<>
<button onClick={clearCanvas}>Clear</button>
<button onClick={getCanvasImage}>Save</button>
</>
)}
</div>
)
}
export default App;
在这个例子中,我们使用 isEmpty() 方法来判断画布是否已经签字。如果是,我们将显示一个提示信息 “Please sign”。如果不是,我们将显示清空和保存按钮。请注意,我们在条件语句中使用了 React 的 Fragment (<> 和 </>),以便向页面上呈现多个元素。
需要注意的是,在 componentDidMount() 阶段,ref 可能不会被立即赋值,因此需要在代码中进行条件检查。