我收到了这个错误:
app.get('/test', (req, res) => {
let Canvas = require('canvas')
, Image = Canvas.Image
, canvas = new Canvas(500, 500)
, ctx = canvas.getContext('2d');
let request = require('request');
let avatar = new Image;
request.get('http://s.4pda.to/pKugVJ7TmgG1Tg5z0SsVLfRCUqTAz2oqz1lz2z2co.jpg', (err, res) => {
avatar.src = res;
ctx.drawImage(avatar, 50, 50 );
});
ctx.font = '30px Impact';
ctx.rotate(.1);
ctx.fillText("Awesome!", 50, 100);
let te = ctx.measureText('Awesome!');
ctx.strokeStyle = 'rgba(0,0,0,0.5)';
ctx.beginPath();
ctx.stroke();
res.setHeader('Content-Type', 'image/png');
canvas.pngStream().pipe(res)
});
尝试这样做时:
{{1}}
我正在使用节点8.3.0,node-canvas 1.6.6,mac os x 10.12.6。 我已经尝试重新安装和重建cairo,jpg / png libs,pixman,node-canvas但它没有帮助我。
答案 0 :(得分:1)
对于研究此问题的任何人,请参阅LinusU于2017年8月13日发表的评论:
https://github.com/Automattic/node-canvas/issues/959
从那里开始,他建议使用这样的方法来加载图像,并等待它的加载:
function loadImage (url) {
return new Promise((resolve, reject) => {
const img = new Canvas.Image()
img.onload = () => resolve(img)
img.onerror = () => reject(new Error('Failed to load image'))
request.get(url, (err, res) => {
if (err) return reject(err)
img.src = res.body
})
})
}
对我来说效果很好。