Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * get a rectangle around color
- * @param {...} ctx 2dCanvasObject to be scanned
- * @return {Object} object storing the rectangle's data (x, y, w(idth), h(eight))
- */
- function getColorBoundsRect(ctx) {
- /**
- * the canvas' context's data property (shorthand)
- * @type {...}
- */
- var data = ctx.data,
- /**
- * counter variable
- * @type {Number}
- */
- i = 0,
- /**
- * the "leftest" pixel that is not black (starts right, as we check if currently looped pixel (that is not black) is "lefter" than the current outerLeftPixel)
- * @type {Number}
- */
- outerLeftPixel = w-1,
- /**
- * the "rightest" pixel that is not black (starts left, as we check if currently looped pixel (that is not black) is "righter" than the current outerRightPixel)
- * @type {Number}
- */
- outerRightPixel = 0,
- /**
- * the "toppest" pixel that is not black (starts at bottom, as we check if currently looped pixel (that is not black) is "topper" than the current outerTopPixel)
- * @type {Number}
- */
- outerTopPixel = h-1,
- /**
- * the "bottomest" pixel that is not black (starts at top, as we check if currently looped pixel (that is not black) is "bottomer" than the current outerBottomPixel)
- * @type {Number}
- */
- outerBottomPixel = 0,
- /**
- * x coordinate of currently looped pixel
- * @type {Number}
- */
- x,
- /**
- * y coordinate of currently looped pixel
- * @type {Number}
- */
- y;
- // loop through all pixels
- // i equals the i'th pixel (0 is the upper left pixel, w*h is the bottom right pixel)
- while (i < (data.length / 4)) {
- // check if currently looped pixel is anything else than black --> color
- if ((data[i*4] + data[i*4+1] + data[i*4+2]) > 0) {
- // set coordinates for the currently looped pixel
- x = i % w; // if one row has 10px and i = 35, the x coordinate of the current pixel is 35 % 10 = 5
- y = Math.floor(i / w); // if one row has 10px and i=35, the y coordinate of the current pixel is 35/10 = 3.5 (--> rounded off = 3)
- // if the x coordinate of the current (colored) pixel is smaller than the current "leftest" pixel, set the x coordinate as new "leftest pixel"
- // same procedure for the other values
- if (x < outerLeftPixel) {
- outerLeftPixel = x;
- }
- if (x > outerRightPixel) {
- outerRightPixel = x;
- }
- if (y < outerTopPixel) {
- outerTopPixel = y;
- }
- if (y > outerBottomPixel) {
- outerBottomPixel = y;
- }
- }
- ++i;
- }
- // if there is color on the canvas, the outer[Right|Left|Bottom|Top]Pixel properties should have been updated accordingly and the following condition should be true
- if (outerRightPixel > outerLeftPixel && outerBottomPixel > outerTopPixel) {
- return {
- x: outerLeftPixel,
- y: outerTopPixel,
- w: outerRightPixel - outerLeftPixel,
- h: outerBottomPixel - outerTopPixel
- };
- }
- // if there is no color on the canvas, return false, as there is no rectangle
- else {
- return false;
- }
- }
Add Comment
Please, Sign In to add comment