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;
            // draw line
            ctx.strokeStyle = color;
            ctx.beginPath();
            // random position length
            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();
        }
    }
 // The text of the number is randomly selected from lowercase Chinese characters, uppercase Chinese characters, and numbers
    const numArr = [
    '〇一二三四五六七八九',
    '0123456789',
    'Zero One Two Three Four Wu Lu Qi Ba Jiu'
    ];
    // first number
    const fir = Math.floor(Math.random() * 10);
    // second number
    const sec = Math.floor(Math.random() * 10);
    // random selection operation
    const operArr = ['Add', 'Subtract', 'Multiply'];
    const oper = Math.floor(Math.random() * operArr.length);


    drawLine();
   //The last number is the abscissa of the text
    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);
//Randomly generate 60 small points of interference
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();
}
    // Calculate the verification code value and save the captcha to the session or redis
    let captcha;
    switch(oper) {
    	case 0:
    	captcha = fir + sec;
    	break;
    	case 1:
    	captcha = fir - sec;
    	break;
    	case 2:
    	captcha = fir * sec;
    	break;
    }
Finally, output var images= canvas.toDataURL() in base64 format; send the value of images to the previous paragraph, and directly assign the value to src in the <img src=""> table tag
As shown in the figure:

Guess you like

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