-
Notifications
You must be signed in to change notification settings - Fork 97
/
captcha.js
58 lines (49 loc) · 1.95 KB
/
captcha.js
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
(function() {
var canvas = require('canvas');
function generate(config, callback) {
config.size = config.size || 4;
config.height = config.height || 24;
config.width = config.width || config.height * config.size;
config.color = config.color || 'rgb(0,0,0)';
config.background = config.background || 'rgb(255,255,255)';
config.text = config.text || ('' + Math.random()).substr(2, config.size);
config.distortion = config.distortion === undefined ? true : config.distortion;
var size = Math.round(config.height * .7),
c = new canvas(config.width, config.height),
context = c.getContext('2d'),
fonts = config.fonts || ['sans-serif', 'serif'],
i;
context.fillStyle = config.background;
context.fillRect(0, 0, config.width, config.height);
context.fillStyle = config.color;
for(i = 0; i < config.text.length; i++) {
context.font = size + 'px ' + fonts[Math.floor(Math.random() * fonts.length)];
if(config.distortion) {
context.setTransform(
Math.random() * 0.25 + 1, // scale horizontally
Math.random() * 0.25, // skew horizontally
Math.random() * 0.25, // skew vertically
Math.random() * 0.25 + 1, // scale vertically
config.height * i + (config.height - size) / 2, // move horizontally
config.height - size / 2 // move vertically
);
} else {
context.setTransform(
1, // scale horizontally
0, // skew horizontally
0, // skew vertically
1, // scale vertically
config.height * i + (config.height - size) / 2, // move horizontally
config.height - size / 2 // move vertically
);
}
context.fillText(config.text.charAt(i), 0, 0);
}
c.toBuffer(function(error, buffer) {
if(error)
throw error;
callback(config.text, buffer);
});
}
module.exports.generate = generate;
})();