Skip to content

Instantly share code, notes, and snippets.

@timdown
Created July 26, 2017 16:15
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save timdown/021d9c8f2aabc7092df564996f5afbbf to your computer and use it in GitHub Desktop.
Save timdown/021d9c8f2aabc7092df564996f5afbbf to your computer and use it in GitHub Desktop.
Returns a copy of a canvas element with surrounding transparent space removed
var trimCanvas = (function() {
function rowBlank(imageData, width, y) {
for (var x = 0; x < width; ++x) {
if (imageData.data[y * width * 4 + x * 4 + 3] !== 0) return false;
}
return true;
}
function columnBlank(imageData, width, x, top, bottom) {
for (var y = top; y < bottom; ++y) {
if (imageData.data[y * width * 4 + x * 4 + 3] !== 0) return false;
}
return true;
}
return function(canvas) {
var ctx = canvas.getContext("2d");
var width = canvas.width;
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var top = 0, bottom = imageData.height, left = 0, right = imageData.width;
while (top < bottom && rowBlank(imageData, width, top)) ++top;
while (bottom - 1 > top && rowBlank(imageData, width, bottom - 1)) --bottom;
while (left < right && columnBlank(imageData, width, left, top, bottom)) ++left;
while (right - 1 > left && columnBlank(imageData, width, right - 1, top, bottom)) --right;
var trimmed = ctx.getImageData(left, top, right - left, bottom - top);
var copy = canvas.ownerDocument.createElement("canvas");
var copyCtx = copy.getContext("2d");
copy.width = trimmed.width;
copy.height = trimmed.height;
copyCtx.putImageData(trimmed, 0, 0);
return copy;
};
})();
@malipetek
Copy link

Works like a charm.

@lovroselic
Copy link

Great solution!

@Lknechtli
Copy link

Thanks for this: works great!

@nikolay-mihaylov
Copy link

Hey, mind adding an example usage?

@TomFranssen
Copy link

Great script!
Is it possible to modify this so that it can trim white (or very close to white) pixels also?

@leandrit1
Copy link

I don't know if it is possible in the client side, to crop or trim the image background based on the corners pixel color, like trimming with packages like SharpJS or imagemagick.
Basically, detect the corner pixel and start trimming it till the point of the pixel color change. Maybe it is too much, but if there is something, it would be a game changer for many.

@DeanVanNiekerk
Copy link

Perfect thanks! 👏

@TCB13
Copy link

TCB13 commented Oct 5, 2022

Thank you ;)

@kaipm
Copy link

kaipm commented Nov 25, 2022

Just what I needed, thank you for sharing this!

@Kutikov
Copy link

Kutikov commented Sep 30, 2023

Cool code, works perfectly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment