The linux server uses node-canvas to draw the image verification code

1. Before installing node-canvas, you need to install some dependencies. Different systems need to be installed differently, take linux as an example:

  • linux: sudo yum install cairo cairo-devel cairomm-devel libjpeg-turbo-devel pango pango-devel pangomm pangomm-devel giflib-devel

  • 安装完依赖后,执行 npm install canvas 即可    

2. Install the font library for linux because the image verification code may need to use Chinese fonts
  • Use yum -y install fontconfig to install fontconfig, use fontconfig to install the font library, you can check whether it is installed before installation, after the installation is successful, you can see the fonts and fontconfig directories in the /usr/shared directory
  • To add Chinese fonts, you can copy them to the linux server in the win7 c:/windows/fonts folder, or download them from the Internet (download from the win7 font library ). After downloading , create a new folder under the /usr/shared/fonts folder. , the folder name is arbitrary, such as: ChineseFonts, then copy the font file in ttf format to this directory and modify the permissions of the folder, hmod -R 755 /usr/share/fonts/ ChineseFonts
  • Install ttmkfdir to search for all font information in the directory, and generate fonts.scale files, enter the command: yum -y install ttmkfdir, then execute the ttmkfdir command: ttmkfdir-e/usr/share/fonts/encodings/encodings.dir, and finally The first step is to modify the font configuration file, first open the configuration file through an editor:vi /etc/fonts/fonts .conf, add <dir> /usr/share/fonts/ ChineseFonts </dir> to the Font directory list, and then Enter: wq to save and exit, and finally don't forget to refresh the font cache in memory, command:fc-cache, you can see the list of many fonts by command: fc -list
3. The code is as follows:
//Generate random numbers
var rn=function(min,max){ return parseInt(Math.random()*(max-min)+min); }
//Generate random color
var rc=function (min,max){ var r = rn (min, max); var g = rn (min, max); var b = rn (min, max); return `rgb(${r},${g},${b})`; }
//canvas
const canvas = new Canvas(100, 30),
	ctx = canvas.getContext('2d');
	ctx.font = '16px "Microsoft YaHei"';
	let height=30,width=100;
// draw text
    let drawText = (text, x) => {
    ctx.save();
        // rotation angle
        const angle = Math.random() / 10;
        //font color
        ctx.fillStyle=rc(10,120);
        ctx.save();
        // y coordinate
        const y = 22;
        ctx.rotate(angle);
        ctx.fillText(text, x, y);
        ctx.restore();
    }
 // draw lines randomly
    let drawLine = () => {
    	const num = Math.floor(Math.random() * 2 + 5);
        // randomly draw a few colored lines
        for (let i = 0; i < num; i++) {
        	const color = '#' + (Math.random() * 0xffffff << 0).toString(16);
        	const y1 = Math.random() * height;
        	const y2 = Math.random() * height;
            // 画线
            ctx.strokeStyle = color;
            ctx.beginPath();
            //随机位置长度
            ctx.moveTo(Math.floor(Math.random() * canvas.width), Math.floor(Math.random() * canvas.height));  
            ctx.lineTo(Math.floor(Math.random() * canvas.width), Math.floor(Math.random() * canvas.height));  
            ctx.lineWidth = 1;  
            ctx.stroke();
        }
    }
 // 数字的文本随机从小写汉字、大写汉字、数字里选择
    const numArr = [
    '〇一二三四五六七八九',
    '0123456789',
    '零壹贰叁肆伍陆柒捌玖'
    ];
    // 第一个数字
    const fir = Math.floor(Math.random() * 10);
    // 第二个数字
    const sec = Math.floor(Math.random() * 10);
    // 随机选取运算
    const operArr = ['加', '减', '乘'];
    const oper = Math.floor(Math.random() * operArr.length);


    drawLine();
   //最后的数字是文本的横坐标
    drawText(numArr[Math.floor(Math.random() * numArr.length)][fir], 10);
    drawText(operArr[oper], 28);
    drawText(numArr[Math.floor(Math.random() * numArr.length)][sec], 50);
    drawText('=', 72);
    drawText('?', 90);
//随机产生60个干扰的小点
for(var i=0;i<60;i++){
	ctx.beginPath();
	ctx.arc(rn(0,width),rn(0,height),1,0,2*Math.PI);
	ctx.closePath();
	ctx.fillStyle=rc(150,200);
	ctx.fill();
}
    // 验证码值的计算,并将captcha的保存到session或者redis中
    let captcha;
    switch(oper) {
    	case 0:
    	captcha = fir + sec;
    	break;
    	case 1:
    	captcha = fir - sec;
    	break;
    	case 2:
    	captcha = fir * sec;
    	break;
    }
最后以base64的格式输出 var images= canvas.toDataURL();把images的值发送给前段,直接把值赋给<img src="">表签中的src
如图:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325722556&siteId=291194637