首頁 > web前端 > js教程 > 主體

使用 node-canvas 繪製驗證碼

高洛峰
發布: 2016-11-19 16:13:52
原創
2228 人瀏覽過

step 1 安裝

在安裝 node-canvas 之前,還需要安裝一些依賴。不同的系統需要安裝的不同,以linux 和mac 為例:

linux: sudo yum install cairo cairo-devel cairomm-devel libjpeg-turbo-devel pango pango-devel pangomm pangomm-devel libjpeg-turbo-devel pango pango-devel pangomm pangomm-devel libjpeg-develrew gif install pkg-config cairo pango libpng jpeg giflib

其他參考 node-canvas#installation

安裝完依賴後,執行 npm install canvas 即可。

step 2 畫圖

透過取得canvas,可以得到context 對象,然後就可以像在前端一樣繪製圖形了

const Canvas = require('canvas');
const canvas = new Canvas(100, 30),
    ctx = canvas.getContext('2d');
登入後複製

實際上我用到的api 和前端的canvas 是一樣的,繪製過程就不多解釋,可以參考canvas 的相關教學。

下面是繪製一個 a + b = ? 的驗證碼

  ctx.font = '24px "Microsoft YaHei"';

  // 绘制文本
  let drawText = (text, x) => {
    ctx.save();
    // 旋转角度
    const angle = Math.random() / 10;
    // y 坐标
    const y = 22;
    ctx.rotate(angle);
    ctx.fillText(text, x, y);
    ctx.restore();
  }

  // 随机画线
  let drawLine = () => {
    const num = Math.floor(Math.random() * 2 + 3);
    // 随机画几条彩色线条
    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.lineTo(0, y1);
      ctx.lineTo(width, y2);
      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], 40);
  drawText(numArr[Math.floor(Math.random() * numArr.length)][sec], 70);
  drawText('=', 100);
  drawText('?', 130);
  
  // 验证码值的计算
  let captcha;
  switch(oper) {
    case 0: 
      captcha = fir + sec;
      break;
    case 1:
      captcha = fir - sec;
      break;
    case 2:
      captcha = fir * sec;
      break;
  }

  // 存入 session
  req.session.captcha = captcha;
登入後複製

效果如下:

使用 node-canvas 繪製驗證碼step 3 回圖片

 canvas.toDataURL(2toDataURL(64 格式資料。

res.send({
  status: 200,
  data: canvas.toDataURL()
})
登入後複製

中文亂碼

在將項目部署到 linux 後,發現輸出顯示的圖片中的中文都變成了方框。

我參考了https://my.oschina.net/u/129529/blog/266843 這篇文章,但是沒有全部運行,而是安裝了

yum cinstall "Chinese Support",yum Fontinstall 。

另外參考https://cnodejs.org/topic/53f98ad8bbdaa79d518c0836 問題裡的 5 樓,使用了微軟雅黑。

還有 issue#461,在字體兩側加上引號。

我照這三個做了,然後 重啟項目 就好了~

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!