Skip to content

Instantly share code, notes, and snippets.

@greggman
Last active January 29, 2024 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greggman/63dee642b2436b3c9f21a19a4a18b8d1 to your computer and use it in GitHub Desktop.
Save greggman/63dee642b2436b3c9f21a19a4a18b8d1 to your computer and use it in GitHub Desktop.
Test offscreen canvas resize WebGL
/*bug-in-github-api-content-can-not-be-empty*/
/*bug-in-github-api-content-can-not-be-empty*/
const canvas = new OffscreenCanvas(1, 1);
const gl = canvas.getContext('webgl');
gl.clearColor(0.25, 0.5, 0.75, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
checkCanvasContents(gl, [64, 128, 191, 255], 'initial');
canvas.width = canvas.width + 1;
checkCanvasContents(gl, [0, 0, 0, 0], 'size change, expect 0,0,0,0');
gl.clearColor(0.25, 0.5, 0.75, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
checkCanvasContents(gl, [64, 128, 191, 255], 'set color, expect 64, 128, 191, 255');
canvas.width = canvas.width;
checkCanvasContents(gl, [64, 128, 191, 255], 'no size change, expect 64, 128, 191, 255 (this is different than HTMLCanvasElement)');
function checkCanvasContents(gl, expected) {
const actual = new Uint8Array(4);
gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, actual);
const same = arrayEquals(expected, actual);
log(`size: ${gl.canvas.width}, ${gl.canvas.height}: ${same ? 'passed': `failed: actual ${actual} != expected: ${expected}`}`)
}
function arrayEquals(a, b) {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
function log(...args) {
const elem = document.createElement('pre');
elem.textContent = args.join(' ');
document.body.appendChild(elem);
}
function checkGLError(gl, expected = 0) {
const err = gl.getError();
passFail(err === expected, 'gl error, expected:', glErrorToString(expected), 'was:', glErrorToString(gl, err));
}
function glEnumToString(gl, value) {
const keys = [];
for (const key in gl) {
if (gl[key] === value) {
keys.push(key);
}
}
return keys.length ? keys.join(' | ') : `0x${value.toString(16)}`;
}
function glErrorToString(gl, value) {
return value === 0 ? 'NONE' : glEnumToString(gl, value);
}
{"name":"Test offscreen canvas resize WebGL","settings":{},"filenames":["index.html","index.css","index.js"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment