我需要在OffscreenCanvas上进行一些绘制,然后将其显示为div元素的背景图像。
最简单的方法是什么?
答案 0 :(得分:3)
最简单的方法是使用OffscreenCanvas.convertToBlob(),在Firefox中也称为 OffscreenCanvas.toBlob()。
根据经验,您不需要dataURL版本。您几乎要对dataURL进行的所有操作都应该改为使用blobURL。
BlobUrl允许我们链接到仅需在内存中存储一次的数据,而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);
}
})();
body{width: 100vw; height: 100vh; margin: 0}
<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>