为什么要在服务端装canvas? 因为并不是所有的客户端都能很好的支持canvas(比如微信小程序不能修改自定义字体),所以我们需要一个
能够在服务端生成图片的,然后将图片传输
安装node-canvas
1. 更新编译环境
sudo apt-get install libcairo2-dev libjpeg8-dev libpango1.0-dev libgif-dev build-essential g++ -y
2. 安装node-canvas
npm install -g canvas
3. 测试代码
var Canvas = require('canvas'),
canvas = new Canvas(300, 200),
ctx = canvas.getContext('2d'),
fs = require('fs');
var out = fs.createWriteStream(__dirname + '/image.png')
, stream = canvas.createPNGStream();
stream.on('data', function(chunk){
out.write(chunk);
});
//在左边画正方形
ctx.fillStyle = '#A00'
ctx.fillRect(0, 30,50,50);
//在右边画正方形
ctx.fillStyle = '#aaa'
ctx.fillRect(50, 30, 50, 50);
//画文字
ctx.fillStyle = "#000";
ctx.font = "20px Arial";
ctx.fillText("Hello World", 0, 20);
//画一个圆
ctx.beginPath();
ctx.arc(30, 110, 20, 0, 2*Math.PI);
ctx.stroke();
ctx.fillStyle = "green";
ctx.fill();
ctx.save();
可能遇到的问题
如果你按上述方法操作,并且运行成功了。那便是极好的
📁
学习笔记
📅
2019-01-16

