nodejs生成验证码

前言

大家都知道原来php有个GD库可以做图片验证码,那么nodejs如何做验证码?带着这个疑问我在google上展开了各种搜索。
终于找到了node-canvas这个node图形包。其原理就是nodejs通过这个包实现了nodejs版本的 canvas 语法,通过调用底层的c语言包来绘制canvas并生成图片。这里只说如何使用,原理不再纠结。

如何安装

安装前请先安装node-canvas依赖的底层包。

  • Mac HomeBrew 安装
1
brew install pkg-config cairo pango libpng jpeg giflib
  • lunix安装
1
sudo apt-get install libcairo2-dev libjpeg8-dev libpango1.0-dev libgif-dev build-essential g++
  • Windows安装

这里windows安装笔记繁琐,所有直接去github查看wiki

以上底层依赖安装好后执行

1
npm install canvas

目前npm下载的是1版本,最新版本请执行

1
npm install canvas@next

nodejs生成验证码demo

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
const express = require('express'); //express
const app = express();
const consolidate = require('consolidate');
app.set('view engine', 'html');
app.set('views', './views');
app.engine('html', consolidate.ejs);
const Canvas = require('canvas');// node-canvas
const Image = Canvas.Image
function mackimage(){
var canvas = new Canvas(80,40)
var ctx = canvas.getContext('2d');
ctx.font = '20px Impact';
var text=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','L','Y','Z','0','1','2','3','4','5','6','7','8','9'];
var randomarr=[];
for(var i=0;i<4;i++){
var random = Math.ceil(Math.random()*35);
randomarr.push(text[random]);
}
ctx.fillText(randomarr.join(''), 10, 30);//canvas 加入随机4位数
var te = ctx.measureText(randomarr.join(''));
ctx.strokeStyle = 'rgba(0,0,0,0.5)';
ctx.beginPath();
ctx.lineTo(50, 102);
ctx.lineTo(50 + te.width, 102);
ctx.stroke();

return canvas.toDataURL();//canvas转img src data64地址
}
//主页面
app.get('/',(req,res)=>{
res.render('index.ejs')
});
//返回验证码图片src
app.get('/getcode',(req,res)=>{
res.send(mackimage());
});
app.listen(3000);

node验证码demo下载

百度网盘传送门

提取密码:w2zw

下载完成后解压缩,安装本文上述依赖包后

1
2
3
4
5
6
7
cd node-canvas

npm i

node server.js

打开浏览器输入localhost:3000/ 查看效果