Skip to content

Instantly share code, notes, and snippets.

@nmrugg
Created August 9, 2022 16:18
Show Gist options
  • Save nmrugg/a8c62a8239100ee7e83a94172896dc81 to your computer and use it in GitHub Desktop.
Save nmrugg/a8c62a8239100ee7e83a94172896dc81 to your computer and use it in GitHub Desktop.
image-pixelated doesn't work in many contexts
canvas {
width: 160px;
height: 160px;
background: orange;
}
.pixelate {
image-rendering: pixelated;
}
.outer {
display: inline-block;
margin: 0.5em;
}
/*bug-in-github-api-content-can-not-be-empty*/
var body = document.getElementsByTagName("body")[0];
var on = true;
body.classList.add("pixelate");
setInterval(function ()
{
if (on) {
body.classList.remove("pixelate");
} else {
body.classList.add("pixelate");
}
on = !on;
}, 500)
function test2D(canvas) {
const ctx = canvas.getContext('2d');
for (let i = 0; i < 8; ++i) {
ctx.fillRect(i, i, 1, 1);
}
}
function testWebGL(canvas) {
const gl = canvas.getContext('webgl');
for (let i = 0; i < 8; ++i) {
gl.clearColor(0, 0, 0, 1);
gl.enable(gl.SCISSOR_TEST);
gl.scissor(i, 7 - i, 1, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
}
}
function testWebGPU(canvas) {
}
function test2DBitmap(canvas) {
const bmCtx = canvas.getContext('bitmaprenderer');
if (!bmCtx) {
return true;
}
const offscreen = new OffscreenCanvas(8, 8);
test2D(offscreen);
const bitmap = offscreen.transferToImageBitmap();
bmCtx.transferFromImageBitmap(bitmap);
}
function testWebGLBitmap(canvas) {
const bmCtx = canvas.getContext('bitmaprenderer');
if (!bmCtx) {
return true;
}
const offscreen = new OffscreenCanvas(8, 8);
testWebGL(offscreen);
const bitmap = offscreen.transferToImageBitmap();
bmCtx.transferFromImageBitmap(bitmap);
}
const tests = [
{name: 'onscreen 2d', fn: test2D, },
{name: 'onscreen webgl', fn: testWebGL },
{name: 'offscreen 2d', fn: test2D, offscreen: true},
{name: 'offscreen WebGL', fn: testWebGL, offscreen: true},
{name: 'bitmaprender 2d', fn: test2DBitmap, },
{name: 'bitmaprender WebGL', fn: testWebGLBitmap, },
];
for (const {name, fn, offscreen} of tests) {
const outer = document.createElement('div');
outer.className = 'outer';
const canvas = document.createElement('canvas');
const text = document.createElement('div');
text.textContent = name;
outer.appendChild(canvas);
outer.appendChild(text);
document.body.appendChild(outer);
canvas.width = 8;
canvas.height = 8;
let failed = false;
let msg = '';
try {
failed = fn(offscreen ? canvas.transferControlToOffscreen() : canvas);
} catch (e) {
failed = true;
msg = e.toString();
}
if (failed) {
text.textContent = `[FAILED]:${name}:${msg}`;
canvas.style.background = 'red';
}
}
{"name":"image-pixelated doesn't work in many contexts","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