Advertisement
xeromino

trimCanvas

Feb 15th, 2022
1,102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // functions to copy just the part with non-transparent pixels
  2. // https://gist.github.com/timdown/021d9c8f2aabc7092df564996f5afbbf
  3.  
  4. function rowBlank(imageData, width2, y) {
  5.       for (var x = 0; x < width2; ++x) {
  6.           if (imageData[y * width2 * 4 + x * 4 + 3] !== 0) return false;
  7.       }
  8.       return true;
  9. }
  10.  
  11. function columnBlank(imageData, width2, x, top, bottom) {
  12.       for (var y = top; y < bottom; ++y) {
  13.           if (imageData[y * width2 * 4 + x * 4 + 3] !== 0) return false;
  14.       }
  15.       return true;
  16. }
  17.  
  18. function trimCanvas(c) {
  19.       var ctx = c;
  20.       var width2 = c.width;
  21.       ctx.loadPixels();
  22.       var top = 0, bottom = c.height, left = 0, right = width2;
  23.  
  24.       while (top < bottom && rowBlank(ctx.pixels, width2, top)) ++top;
  25.       while (bottom - 1 > top && rowBlank(ctx.pixels, width2, bottom - 1)) --bottom;
  26.       while (left < right && columnBlank(ctx.pixels, width2, left, top, bottom)) ++left;
  27.       while (right - 1 > left && columnBlank(ctx.pixels, width2, right - 1, top, bottom)) --right;
  28.  
  29.       var trimmedWidth = right - left , trimmedHeight = bottom - top;
  30.       var trimmed = ctx.get(left, top, trimmedWidth,trimmedHeight);
  31.  
  32.       image(trimmed,0,0, trimmed.width*.66, trimmed.height*.66);
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement