koa(五) svg-captcha 生成图片验证码

使用svg-captcha可以比较方便的生成图片验证码

安装

npm install --save svg-captcha

使用

1
2
3
4
5
const svgCaptcha = require('svg-captcha');

const c = svgCaptcha.create();
console.log(c);
// {data: '<svg.../svg>', text: 'abcd'}
  1. 生成普通验证码
  1. 生成算式验证码
1
let captcha = svgCaptcha.createMathExpr();

options参数

  • size: 4 // 验证码长度
  • ignoreChars: ‘0o1i’ // 验证码字符中排除 0o1i
  • noise: 1 // 干扰线条的数量
  • color: true // 验证码的字符是否有颜色,默认没有,如果设定了背景,则默认有
  • background: ‘#cc9966’ // 验证码图片背景颜色
  • fontSize: 50
  • width: 100
  • height:40

在koa中使用

前端请求一个URL返回一个验证码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

//验证码
router.get('/code', async (ctx) => {
let captcha = svgCaptcha.create({
size: 4,
fontSize: 50,
noise: 3,
width: 120,
height: 34,
background: "#cc9966"
});

ctx.session.code = captcha.text;
//设置响应头
ctx.response.type = "image/svg+xml";
ctx.body = captcha.data;
});