我需要在OffscreenCanvas上进行一些绘制,然后将其显示为div元素的背景图像。
最简单的方法是什么?
最佳答案
最简单的方法是使用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>
关于javascript - 如何将OffscreenCanvas转换为DataURI,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54523077/