Skip to content

Instantly share code, notes, and snippets.

@pdkovacs
Created October 25, 2019 15:37
Show Gist options
  • Save pdkovacs/c1236edca2fe0a42308b380bb4043a90 to your computer and use it in GitHub Desktop.
Save pdkovacs/c1236edca2fe0a42308b380bb4043a90 to your computer and use it in GitHub Desktop.
Calculate bounding box for content on an HTML5 Canvas
const contextBoundingBox = (ctx: CanvasRenderingContext2D, alphaThreshold: number) => {
const effectiveAlphaThrh = alphaThreshold || 15;
const w = ctx.canvas.width;
const h = ctx.canvas.height;
const data = ctx.getImageData(0, 0, w, h).data;
let x: number;
let y: number;
let minX: number;
let minY: number;
let maxX: number;
let maxY: number;
o1: {
for (y = h; y--;) {
for (x = w; x--;) {
if (data[(w * y + x) * 4 + 3] > effectiveAlphaThrh) {
maxY = y;
break o1;
}
}
if (!maxY) {
return;
}
}
o2: {
for (x=w;x--;) {
for (y=maxY+1;y--;) if (data[(w*y+x)*4+3]>effectiveAlphaThrh){ maxX=x; break o2 }
o3: for (x=0;x<=maxX;++x) for (y=maxY+1;y--;) if (data[(w*y+x)*4+3]>effectiveAlphaThrh){ minX=x; break o3 }
o4: for (y=0;y<=maxY;++y) for (x=minX;x<=maxX;++x) if (data[(w*y+x)*4+3]>effectiveAlphaThrh){ minY=y; break o4 }
return {x:minX,y:minY,maxX:maxX,maxY:maxY,w:maxX-minX,h:maxY-minY};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment