0

我收到此错误:

        ctx.drawImage(avatar, 50, 50 );
            ^

Error: Image given has not completed loading
    at Request.request.get

尝试执行此操作时:

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)
});

我正在使用节点 8.3.0、节点画布 1.6.6、mac os x 10.12.6。我已经尝试重新安装和重建 cairo、jpg/png 库、pixman、node-canvas,但它对我没有帮助。

4

1 回答 1

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
    })
  })
}

它对我很有效。

于 2018-04-27T13:08:21.880 回答