createImageBitmap返回空图像

时间:2018-10-24 02:01:31

标签: javascript image

我正在使用createImageBitmap在工作程序中转换图像。

blob进入时有数据,定位有效(它们是负数,但我尝试使用0和相同的问题)

 createImageBitmap(blob, -pos.x + 100, -pos.y + 100, 200, 200).then(data => {
            resolve(data)})

输出的数据为<ImageData width: 200, height 200 />

但是什么时候尝试将其转换为blob

const canvas = document.createElement('canvas')
      canvas.height = img.height
      canvas.width = img.width
      const context = canvas.getContext('bitmaprenderer')
      context.transferFromImageBitmap(img)

canvas.toBlob((blob)=> ..

blob为空。

关于我要去哪里的任何线索吗?

1 个答案:

答案 0 :(得分:1)

这是一个Chrome bug,带有bitmaprenderer上下文...

无论出于何种原因,HTMLCanvasElement.toBlob()HTMLCanvasElement.toDataURL()的结果将是完全透明的图像...

它们不支持HTMLCanvasElement中显示的当前活动位图缓冲区。

这可以通过将画布附加到文档来证明:

fetch('https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png')
  .then(r => r.blob())
  .then(b=>createImageBitmap(b, 120,120,120,120))
  .then(img => {
    return new Promise(res => {
      // create a canvas
      const canvas = document.createElement('canvas');
      // resize it to the size of our ImageBitmap
      canvas.width = img.width;
      canvas.height = img.height;
      document.body.append(canvas);
      // transfer on the bitmarenderer context
      canvas.getContext('bitmaprenderer')
        .transferFromImageBitmap(img);
      // get it back as a Blob
      canvas.toBlob(res);
    });
  })
  .then(blob => {
    var img = document.body.appendChild(new Image());
    img.src = URL.createObjectURL(blob);
  });
img {
  border: solid red;
}
canvas {
  border: solid green;
}

您可以给the issue加上星号,以使其具有更高的优先级,并且暂时来说,您可能希望回退到2dContext及其内存消耗 drawImage()方法... < / p>

fetch('https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png')
  .then(r => r.blob())
  .then(b=>createImageBitmap(b, 120,120,120,120))
  .then(img => {
    return new Promise(res => {
      // create a canvas
      const canvas = document.createElement('canvas');
      // resize it to the size of our ImageBitmap
      canvas.width = img.width;
      canvas.height = img.height;
      document.body.append(canvas);
      // draw on a 2d context
      canvas.getContext('2d')
        .drawImage(img,0,0);
      // get it back as a Blob
      canvas.toBlob(res);
    });
  })
  .then(blob => {
    var img = document.body.appendChild(new Image());
    img.src = URL.createObjectURL(blob);
  });
img {
  border: solid red;
}
canvas {
  border: solid green;
}