如何将 OffscreenCanvas 转换为 DataURI

Val*_*rii 0 javascript canvas html5-canvas

我需要在 OffscreenCanvas 上做一些绘图,然后将其显示为 div 元素的背景图像。

最简单的方法是什么?

Kai*_*ido 5

对您来说最简单的是使用OffscreenCanvas.convertToBlob(),在 Firefox 中也称为OffscreenCanvas.toBlob()

根据经验,您不需要 dataURL 版本。几乎所有你想用 dataURL 做的事情都应该用 blobURL 来完成。
BlobUrls 允许我们链接到只需要在内存中存储一​​次的数据,而 dataURI 每次以字符串形式出现时将获取所需数据的 134% + 每次获取时获取实际数据的 100%。

(function() {
const worker = new Worker(generateWorkerURL());
worker.onmessage = e => {
  // generate a blobURI from the Blob
  const url = URL.createObjectURL(e.data.blob);
  // use it
  document.body.style.backgroundImage = `url(${url})`;
};

const canvas = document.createElement('canvas');
canvas.width = canvas.height = 100;
const offscreen = canvas.transferControlToOffscreen();

worker.postMessage({canvas: offscreen}, [offscreen]);

function generateWorkerURL() {
  const scr = document.querySelector('[type="worker-script"]');
  const cont = scr.textContent;
  const blob = new Blob([cont], {type: 'text/javascript'});
  return URL.createObjectURL(blob);
}
})();
Run Code Online (Sandbox Code Playgroud)
body{width: 100vw; height: 100vh; margin: 0}
Run Code Online (Sandbox Code Playgroud)
<script type="worker-script">
  onmessage = e => {
    const canvas = e.data.canvas;
    // red squares 
    const gl = canvas.getContext('webgl');
    gl.viewport(0, 0,
    gl.drawingBufferWidth, gl.drawingBufferHeight);
    gl.enable(gl.SCISSOR_TEST);
    gl.scissor(20, 20, 60, 60);

    gl.clearColor(1.0, 0.0, 0.0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);
    // export as Blob
    (canvas.convertToBlob || canvas.toBlob).call(canvas)
    .then(blob => {
      postMessage({blob});
    });

  }

</script>
Run Code Online (Sandbox Code Playgroud)

  • 不,使用 HTMLCanvasElement taht 你不附加到文档也会做同样的事情,并有更好的浏览器支持。OffscreeenCanvas 适用于没有 DOM 的上下文(即工人) (2认同)