javascript - Webworker OffscreenCanvas draw regular image - Stack Overflow

Webworkers can fetch regular images through XMLHttpRequest, right? How can the workers then draw these

Webworkers can fetch regular images through XMLHttpRequest, right? How can the workers then draw these images to OffscreenCanvas? Probably want to use XMLHttp.responseType = 'blob'?

Another way would be to set the src of an image element and then transfer the element to worker, but my workers always reject such images.

Thanks

Webworkers can fetch regular images through XMLHttpRequest, right? How can the workers then draw these images to OffscreenCanvas? Probably want to use XMLHttp.responseType = 'blob'?

Another way would be to set the src of an image element and then transfer the element to worker, but my workers always reject such images.

Thanks

Share Improve this question asked Jun 12, 2019 at 0:42 ituyituy 2414 silver badges11 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

The ImageBitmap API is here for this purpose (among others).

Note: this demo will currently run only on Chrome...

const offcanvas = canvas.transferControlToOffscreen();
const worker = new Worker(getWorkerURL());
worker.onmessage = e => console.log(e.data);
worker.postMessage(offcanvas, [offcanvas]);


function getWorkerURL() {
  return URL.createObjectURL(
    new Blob([
      worker_script.textContent
    ])
  );
}
<canvas id="canvas" height="450"></canvas>

<script id="worker_script" type="ws">
onmessage = async (evt) => {
  try {
    const canvas = evt.data;
    const ctx = canvas.getContext('2d');
    if(!ctx) {
      postMessage('unsupported browser');
      return;
    }
    const imgblob = await fetch('https://upload.wikimedia/wikipedia/mons/5/55/John_William_Waterhouse_A_Mermaid.jpg')
      .then(r => r.blob());
    const img = await createImageBitmap(imgblob);
    ctx.drawImage(img, 0,0, canvas.width, canvas.height);
 }
 catch(e) {
  postMessage('unsupported browser');
  throw e;
  }
};
</script>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744237087a4564521.html

相关推荐

  • javascript - Webworker OffscreenCanvas draw regular image - Stack Overflow

    Webworkers can fetch regular images through XMLHttpRequest, right? How can the workers then draw these

    8天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信