2015
Mar
07

PHP 用來畫圖的 Library 叫做 PHP GD ,而 Javascript 有個 library 叫 canvas ,也是用來畫圖的,有人已經在 Node.js 開發出 Node.js Canvas ,我們只要安裝這個 Package ,就能在 Server 端寫程式來畫圖。

Node.js 也有 GD 的版本可以用來畫圖,但是我不建議做用 GD ,原因為若我們使用 Canvas 來畫圖,那麼也同時可以學會在 Browser 裡使用 Canvas ,一次學會 Web Server 端與 Client 端的畫圖方式。

下面這個網址有一些簡單的使用範本



Node.js Canvas 有用到其它的 Open Source ,所以我們也得安裝這些 library ,我的系統是 CentOS ,平常都是使用 yum 來安裝 Package。

  • sudo yum install pango-devel
  • sudo yum install cairo-devel
  • sudo yum install giflib-devel
  • sudo yum install libpng-devel

安裝好以上 Package 後,再來就用 npm install 來裝上  canvas

  • npm install canvas

來畫一張 Canvas Hello World 吧

Example
  1. var Canvas = require('canvas'),
  2. canvas = new Canvas(150, 150),
  3. ctx = canvas.getContext('2d'),
  4. fs = require('fs');
  5.  
  6. var out = fs.createWriteStream(__dirname + '/image.png')
  7. , stream = canvas.createPNGStream();
  8.  
  9. stream.on('data', function(chunk){
  10. out.write(chunk);
  11. });
  12.  
  13. //在左邊畫正方形
  14. ctx.fillStyle = '#A00'
  15. ctx.fillRect(0, 30,50,50);
  16. ctx.save();
  17.  
  18. //在右邊畫正方形
  19. ctx.fillStyle = '#aaa'
  20. ctx.fillRect(50, 30, 50, 50);
  21.  
  22. //畫文字
  23. ctx.fillStyle = "#000";
  24. ctx.font = "20px Arial";
  25. ctx.fillText("Hello World", 0, 20);
  26.  
  27. //畫一個圓
  28. ctx.beginPath();
  29. ctx.arc(30, 110, 20, 0, 2*Math.PI);
  30. ctx.stroke();
  31. ctx.fillStyle = "green";
  32. ctx.fill();

相關資料


回應 (Leave a comment)