Webworker OffscreenCanvas绘制常规图像 [英] Webworker OffscreenCanvas draw regular image

查看:129
本文介绍了Webworker OffscreenCanvas绘制常规图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Webworkers可以通过 XMLHttpRequest 获取常规图像,对吗?然后工人如何将这些图像绘制到OffscreenCanvas?可能想使用 XMLHttp.responseType ='blob'

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'?

另一种方法是设置 src 的图像元素,然后将其转移给工作人员,但我的工作人员始终拒绝此类图像。

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.

谢谢

推荐答案

ImageBitmap API 用于此目的(以及其他目的)。

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

注意:该演示当前将运行仅在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.org/wikipedia/commons/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>

这篇关于Webworker OffscreenCanvas绘制常规图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆