Created
May 27, 2019 17:07
-
-
Save lovasoa/f10af24bc57d8997427a2204b7e189c9 to your computer and use it in GitHub Desktop.
Compute the maximum available canvas width and height in a browser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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