什么是svg-captcha?

svg-captcha顾名思义,就是使用svg成验证码的一个库,使用opentype.js将字符转换为svg路径,然后生成验证码,不需要任何 c++ 模块,十分的小巧。

svg-captcha相比与其他方案比如node-canvas有什么优点?

  1. node-canvas安装十分烦琐,参考https://github.com/Automattic/node-canvas#installation要安装大量的第三方c++的模块,体积十分大。
  2. 在windows上https://github.com/Automattic/node-canvas/wiki/Installation---Windows安装要安装很多多于的模块组件。
  3. 而svg-captcha却没有那些缺点,只需要安装一个模块即可在所有平台上轻松运行。
  4. 生成图片的大小和速度均适中:相比于 bmp 要小得多(150x50只有5k左右,而bmp100x40就要11k)比 png 要小(但也要看复杂度)
  5. 速度足够快,最低能达到1700张/s

安装使用

npm install --save svg-captcha
var svgCaptcha = require('svg-captcha');
var c = svgCaptcha.create();
console.log(c);
# {data: '<svg.../svg>', text: 'abcd'}

API

svgCaptcha.create(options)

如果没有任何参数,则生成的 svg 图片有4个字符。

  • size: 4 // 验证码长度
  • ignoreChars: '0o1i' // 验证码字符中排除 0o1i
  • noise: 1 // 干扰线条的数量
  • color: true // 验证码的字符是否有颜色,默认没有,如果设定了背景,则默认有
  • background: '#cc9966' // 验证码图片背景颜色
    该函数返回的对象拥有以下属性
  • data: string // svg 路径
  • text: string // 验证码文字

svgCaptcha.createMathExpr(options)

和前面的 api 的参数和返回值都一样。不同的是这个 api 生成的 svg 是一个算数式,而 text 属性上是算数式的结果。不过用法和之前是完全一样的。

svgCaptcha.loadFont(url)

加载字体,覆盖内置的字体。
url: string // 字体文件存放路径 该接口会调用opentype.js同名的接口。 你可能需要更改一些配置才能让你得字体好看。
详见下面的这个接口:

svgCaptcha.options

这是全局配置对象。 create和createMathExpr接口的默认配置就是使用的这个对象。

除了 size, noise, color, 和 background 之外,你还可以修改以下属性:

width: number // width of captcha  
height: number // height of captcha  
fontSize: number // captcha text size  
charPreset: string // random character preset

svgCaptcha.randomText([size|options])

返回随机字符串

svgCaptcha(text, options)

返回基于text参数生成得svg路径