Skip to content

Instantly share code, notes, and snippets.

@iampava
Last active June 9, 2020 07:16
Show Gist options
  • Save iampava/3921e669b69d17c6ea44192dbff08415 to your computer and use it in GitHub Desktop.
Save iampava/3921e669b69d17c6ea44192dbff08415 to your computer and use it in GitHub Desktop.
Offscreen Canvas width limitation?
/**
At this canvas width, the normal one gets rendered but the offscreen one is still empty.
However, if you change this to a lower number both will work.
*/
const WIDTH = 20000;
const [firstCanvas, secondCanvas] = document.querySelectorAll('canvas');
firstCanvas.width = WIDTH;
secondCanvas.width = WIDTH;
const offscreen = secondCanvas.transferControlToOffscreen()
const worker = new Worker('/worker.js');
worker.postMessage({
key: 'CANVAS',
payload: {
canvas: offscreen
}
}, [offscreen])
drawOnCanvases();
function clearCanvases() {
worker.postMessage({ key: 'CLEAR' })
firstCanvas.getContext('2d').clearRect(0, 0, firstCanvas.width, firstCanvas.height)
};
function drawOnCanvases() {
worker.postMessage({ key: 'DRAW' })
const firstCtx = firstCanvas.getContext('2d')
firstCtx.fillStyle = 'red'
firstCtx.fillRect(0, 0, firstCanvas.width, firstCanvas.height / 2)
};
// In case you wanna interact with it from the Browser Console
window.clearCanvases = clearCanvases
window.drawOnCanvases = drawOnCanvases
<!DOCTYPE html>
<html lang="en">
<head>
<title>Offscreen Canvas width limitation???</title>
<style>
canvas {
border: 5px solid navy;
margin-bottom: 50px;
}
</style>
</head>
<body>
<canvas height="48"></canvas>
<canvas height="48"></canvas>
<script src="app.js"></script>
</body>
</html>
let canvas;
onmessage = function (evt) {
switch (evt.data.key) {
case 'CANVAS':
canvas = evt.data.payload.canvas
break
case 'CLEAR':
canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height)
break
case 'DRAW': {
const ctx = canvas.getContext('2d')
ctx.fillStyle = 'red'
ctx.fillRect(0, 0, canvas.width, canvas.height / 2)
break
}
default:
break
}
}
@iampava
Copy link
Author

iampava commented Jun 9, 2020

Tested on the latest versions of Chrome (including Canary) and Edge. On the latest Firefox Nightly, after turning on gfx.offscreencanvas.enabled still crashes. I guess it's not implemented there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment