-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCaptcha.tsx
83 lines (71 loc) · 1.77 KB
/
Captcha.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import React, { Component } from 'react';
function getRandomColor() {
return '#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).substr(-6);
}
interface IProps {
text: string;
width?: number;
height?: number;
fontSize?: number;
onClick?(): void;
}
interface IState { }
export default class Captcha extends Component<IProps, IState> {
private canvas: React.RefObject<HTMLCanvasElement>;
static defaultProps = {
width: 60,
height: 30,
fontSize: 14,
}
constructor(props) {
super(props);
this.canvas = React.createRef();
}
componentDidMount() {
this.draw();
}
componentDidUpdate(prevProps) {
if (prevProps.text != this.props.text) {
this.draw();
}
}
draw() {
const { text, width, height, fontSize } = this.props;
if (text) {
const ctx = this.canvas.current.getContext('2d');
ctx.clearRect(0, 0, width, height);
ctx.font = "14px serif";
const letters = text.split('');
const averageWidth = (width - fontSize) / letters.length;
letters.forEach((letter, index) => {
const x = averageWidth * index + fontSize / 2;
const y = (height + fontSize) / 2;
const radian = Math.random() < 0.5
? -Math.PI / 180 * Math.random() * 15
: Math.PI / 180 * Math.random() * 15;
ctx.translate(x, 0);
ctx.rotate(radian);
ctx.fillStyle = getRandomColor();
ctx.fillText(letter, 0, y);
ctx.rotate(-radian);
ctx.translate(-x, 0);
});
}
}
render() {
const {
width,
height,
onClick,
} = this.props;
return (
<canvas
className="cm-captcha"
ref={this.canvas}
width={width}
height={height}
onClick={onClick}
/>
);
}
}