Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Created May 27, 2019 17:07
Show Gist options
  • Save lovasoa/f10af24bc57d8997427a2204b7e189c9 to your computer and use it in GitHub Desktop.
Save lovasoa/f10af24bc57d8997427a2204b7e189c9 to your computer and use it in GitHub Desktop.
Compute the maximum available canvas width and height in a browser
async function maxCanvasSize(ratio) {
let cvs = document.createElement("canvas");
let xmin = 1, xmax = 1 << 18;
while (xmax - xmin > 1) {
let x = ((xmin + xmax) / 2) | 0;
let y = (x / ratio) | 0;
if (await canvasTest(cvs, x, y)) xmin = x;
else xmax = x;
}
return [xmin, xmin / ratio | 0];
}
function canvasTest(cvs, width, height) {
return new Promise(a => {
try {
cvs.width = width;
cvs.height = height;
let ctx = cvs.getContext("2d");
ctx.fillRect(width - 1, height - 1, 1, 1);
return a(!!ctx.getImageData(width - 1, height - 1, 1, 1).data[3]);
}
catch (e) {
return a(false);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment