Skip to content

Instantly share code, notes, and snippets.

@doxas
Created September 19, 2019 13:28
Show Gist options
  • Save doxas/bdeec25a3c8c75bb0eb377e86aad053c to your computer and use it in GitHub Desktop.
Save doxas/bdeec25a3c8c75bb0eb377e86aad053c to your computer and use it in GitHub Desktop.
function powerOfTwo(v){
return (v & (v - 1)) === 0;
}
function nearPowerOfTwo(v){
if(v <= 0){return 0;}
let w = v;
w = w | (w >> 1);
w = w | (w >> 2);
w = w | (w >> 4);
w = w | (w >> 8);
w = w | (w >> 16);
return w + 1;
}
// example with canvas
if(
object instanceof HTMLImageElement === true &&
(powerOfTwo(object.naturalWidth) !== true || powerOfTwo(object.naturalHeight) !== true)
){
let nearWidth = nearPowerOfTwo(object.naturalWidth);
let nearHeight = nearPowerOfTwo(object.naturalHeight);
let c = document.createElement('canvas');
let cx = c.getContext('2d');
c.width = nearWidth;
c.height = nearHeight;
cx.drawImage(object, 0, 0, nearWidth, nearHeight);
obj = c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment