Created
January 15, 2017 00:03
-
-
Save dei-biz/73352aa0a7dc09ccf7f257943600b4a1 to your computer and use it in GitHub Desktop.
find boundary box of non transparent pixels on a <canvas>
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
| 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