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', // 驗證碼字符中排除 0o1inoise: 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', // 驗證碼字符中排除 0o1inoise: 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', // 驗證碼字符中排除 0o1inoise: 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)
})