网络工作者可以通过XMLHttpRequest
获取常规图像,对吗?工人如何将这些图像绘制到OffscreenCanvas?可能要使用XMLHttp.responseType = 'blob'
?
另一种方法是设置图像元素的src
,然后将其传送给工作人员,但我的工作人员总是拒绝此类图像。
谢谢
答案 0 :(得分:1)
ImageBitmap API用于此目的(以及其他目的)。
注意:此演示当前仅在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>