react-signature-canvas git 地址
代码示例
import React, { Component } from 'react'
import { createRoot } from 'react-dom/client'
import SignaturePad from '../../src/index.tsx'
import * as styles from './styles.module.css'
class App extends Component {
state = { trimmedDataURL: null }
isErasing = false;
sigPad = {}
clear = () => {
this.sigPad.clear()
}
trim = () => {
this.setState({
trimmedDataURL: this.sigPad.getTrimmedCanvas().toDataURL('image/png')
})
}
// 恢复画笔功能
bruser = ()=>{
this.isErasing = false;
const canvas = this.sigPad._canvas;
if (!this.isErasing && canvas) {
const ctx = canvas.getContext('2d');
ctx.globalCompositeOperation = 'source-over';
}
}
//橡皮擦功能
handleErase = () => {
this.isErasing = !this.isErasing;
const canvas = this.sigPad._canvas;
// 设置橡皮擦属性及样式
if (this.isErasing && canvas) {
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#e21061';
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.arc(canvas.offsetLeft, canvas.offsetTop, 10, 0, 2 * Math.PI);
ctx.fill();
}
}
render() {
const { trimmedDataURL } = this.state
return <div className={styles.container}>
<div className={styles.sigContainer}>
<SignaturePad canvasProps={{
className: styles.sigPad,
}}
options={{
minWidth: 0.5, // 最小线条宽度
maxWidth: 2, // 最大线条宽度
penColor: "black" // 笔的颜色
}}
ref={(ref) => { this.sigPad = ref }} />
</div>
<div style={{display:'flex',alignItems:'center',justifyContent:'space-around'}}>
<button className={styles.buttons} onClick={this.clear}>
Clear
</button>
<button className={styles.buttons} onClick={this.trim}>
Trim
</button>
<button className={styles.buttons} onClick={this.bruser}>
Bruser
</button>
<button className={styles.buttons} onClick={this.handleErase}>
Erase
</button>
</div>
{trimmedDataURL
? <img className={styles.sigImage} alt='signature'
src={trimmedDataURL} />
: null}
</div>
}
}
createRoot(document.getElementById('container')).render(<App />)
画笔成果展示:
橡皮擦擦除之后的效果: