1. 安裝svg-captcha
$ npm install --save svg-captcha
2. 使用方法
- 生成有4個字符的圖片和字符串
const svgCaptcha = require('svg-captcha')
const cap = svgCaptcha.create({
size: 4, // 驗證碼長度
width:160,
height:60,
fontSize: 50,
ignoreChars: '0oO1ilI', // 驗證碼字符中排除 0o1i
noise: 2, // 干擾線條的數量
color: true, // 驗證碼的字符是否有顏色,默認沒有,如果設定了背景,則默認有
background: '#eee' // 驗證碼圖片背景顏色
})
console.log(c);
// {data: '<svg.../svg>', text: 'abcd'}
如圖:
- 生成一個算術式和計算結果
const cap = svgCaptcha.createMathExpr({
size: 4, // 驗證碼長度
width:160,
height:60,
fontSize: 50,
ignoreChars: '0oO1ilI', // 驗證碼字符中排除 0o1i
noise: 2, // 干擾線條的數量
color: true, // 驗證碼的字符是否有顏色,默認沒有,如果設定了背景,則默認有
background: '#eee' // 驗證碼圖片背景顏色
})
如圖:
3. 在 koa2 項目中使用
const Koa = require('koa');
const Router = require('koa-router') // koa 路由中間件
const svgCaptcha = require('svg-captcha')
const app = new Koa();
const router = new Router(); // 實例化路由
router.get('/home', async (ctx, next) => {
const cap = svgCaptcha.create({
size: 4, // 驗證碼長度
width:160,
height:60,
fontSize: 50,
ignoreChars: '0oO1ilI', // 驗證碼字符中排除 0o1i
noise: 2, // 干擾線條的數量
color: true, // 驗證碼的字符是否有顏色,默認沒有,如果設定了背景,則默認有
background: '#eee' // 驗證碼圖片背景顏色
})
let img = cap.data // 驗證碼
let text = cap.text.toLowerCase() // 驗證碼字符,忽略大小寫
ctx.type = 'html'
ctx.body = `${img}<br><a href="javascript: window.location.reload();">${text}</a>`
});
app.use(router.routes());
app.listen(3333, () => {
console.log('This server is running at http://localhost:' + 3333)
})