一般情况不论用什么工具, 都要先生成图片的buffer, 然后输出就好了. 有那么几个库:

  1. jimp, 这个是我用的

    1. https://www.npmjs.com/package/jimp
    2. https://github.com/oliver-moran/jimp
  2. yahoo的pngjs, 貌似已经停止维护了:

    1. https://www.npmjs.com/package/pngjs
    2. https://github.com/yahoo/pngjs-image
  3. sharp

    1. https://github.com/lovell/sharp
    2. http://sharp.pixelplumbing.com/en/stable/api-output/
  4. gm据说占有率挺高的.

  5. canvas

    canvas.toDataURL()// 这个是啥情况?
    //https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLCanvasElement/toDataURL
    //这个会返回一个base64的png文件
    
  6. 貌似fs可以直接写png文件

    require("fs").writeFile("out.png", base64Data, 'base64', function(err) {
      console.log(err);
    });
    
最终方案
  • 我用了canvas:) https://www.npmjs.com/package/canvas
    • 这个很方便.
  • 参考了这个, https://stackoverflow.com/questions/35137936/can-i-let-node-js-generate-a-canvas-without-an-html-page
    • 这个答案很棒, 他给我指明了出路, 不过这里面的写法都比较古老了. 所以要根据canvas官方的写法来修改.
    • 神奇的是, 这个问题的评分是0分, 这个答案的评分是一分, 神奇死了.
  • 另一个方案用canvas.toDataURL应该也是可以的. 而且可能会更简单且灵活一些.
//canvas输出文件核心代码:
let j =0;
  canvas[j] = createCanvas(200, 200);
    ctx[j] = canvas[j].getContext('2d');
    ctx[j].beginPath();
    ctx[j].lineWidth = 30;
    ctx[j].fillStyle = colors[j];
    ctx[j].arc(100, 100, 50, 0, 2 * Math.PI); 
    ctx[j].fill();
    ctx[j].strokeStyle = grayborder[k];
    ctx[j].stroke();
    stream[j] = canvas[j].pngStream();
    var out = fs.createWriteStream('png/can'+i+'.png');
    stream[j].pipe(out);

canvas.toDataURL的代码没有真的去实现, 有兴趣的小伙伴如果做了, 把结果和我说一声…….

在一周之后, 我重写了这个部分, 改为todataurl实现. 确实更方便.
//代码和上面一毛一样, 就是改为输出一个url数组就好了. 
//canvas输出文件核心代码:
let j =0;
let out =[];
canvas[j] = document.createElement("canvas"); //这句话针对网页环境有改变. 特别要注意这句话, 'canvas'换成'div'下面一句话就报错了. 奶奶的....
   ctx[j] = canvas[j].getContext('2d');
    ctx[j].beginPath();
    ctx[j].lineWidth = 30;
    ctx[j].fillStyle = colors[j];
    ctx[j].arc(100, 100, 50, 0, 2 * Math.PI); 
    ctx[j].fill();
    ctx[j].strokeStyle = grayborder[k];
    ctx[j].stroke();
    out.push(canvas[j].toDataURL())

特别注意上面的canvas[j] = document.createElement(“div”);这么写, 就会报错:Uncaught TypeError: canvas[j].getContext is not a function

是我看书不仔细, mdn写的很清楚: canvas是元素
  • https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API/Tutorial/Basic_usage
更多

然后我还发现这个: canvas.toBlob, canvas有相当多的实用功能啊.

//canvas直接在页面中build的时候, 可以设置高宽.
function createContext(width, height) {
    var canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    return canvas.getContext("2d");
}