Skip to content

Instantly share code, notes, and snippets.

@dei-biz
Created January 15, 2017 00:03
Show Gist options
  • Select an option

  • Save dei-biz/73352aa0a7dc09ccf7f257943600b4a1 to your computer and use it in GitHub Desktop.

Select an option

Save dei-biz/73352aa0a7dc09ccf7f257943600b4a1 to your computer and use it in GitHub Desktop.
find boundary box of non transparent pixels on a <canvas>
var findBB = function(canvas){
var width = canvas.width;
var height = canvas.height;
var imageData = canvas.getContext('2d').getImageData(0,0,width,height);
var data = imageData.data;
var bounds = {
xMax : 0,
xMin : width,
yMax : 0,
yMin : height
};
var derecha = 0;
for (var i=0;i<width*height*4;i+=4){
if (data[i+3] !== 0){
var pos = offset2xy(i/4, width, height);
//alpha = 0
if (pos.x > bounds.xMax){
bounds.xMax = pos.x;
}
if (pos.x < bounds.xMin){
bounds.xMin = pos.x;
}
if (bounds.yMax < pos.y){
bounds.yMax = pos.y;
}
if (bounds.yMin > pos.y){
bounds.yMin = pos.y;
}
}
}
canvas.getContext('2d').putImageData(imageData, 0,0)
return bounds;
function offset2xy(offset, width, height){
return {
y : Math.floor(offset/width),
x : offset%width
};
}
function xy2offset(x,y, width){
return y*width+x;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment