Skip to content

Instantly share code, notes, and snippets.

@remy
Last active May 3, 2024 13:39
Show Gist options
  • Star 93 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save remy/784508 to your computer and use it in GitHub Desktop.
Save remy/784508 to your computer and use it in GitHub Desktop.
Trims the surrounding transparent pixels from a canvas
// MIT http://rem.mit-license.org
function trim(c) {
var ctx = c.getContext('2d'),
copy = document.createElement('canvas').getContext('2d'),
pixels = ctx.getImageData(0, 0, c.width, c.height),
l = pixels.data.length,
i,
bound = {
top: null,
left: null,
right: null,
bottom: null
},
x, y;
for (i = 0; i < l; i += 4) {
if (pixels.data[i+3] !== 0) {
x = (i / 4) % c.width;
y = ~~((i / 4) / c.width);
if (bound.top === null) {
bound.top = y;
}
if (bound.left === null) {
bound.left = x;
} else if (x < bound.left) {
bound.left = x;
}
if (bound.right === null) {
bound.right = x;
} else if (bound.right < x) {
bound.right = x;
}
if (bound.bottom === null) {
bound.bottom = y;
} else if (bound.bottom < y) {
bound.bottom = y;
}
}
}
var trimHeight = bound.bottom - bound.top,
trimWidth = bound.right - bound.left,
trimmed = ctx.getImageData(bound.left, bound.top, trimWidth, trimHeight);
copy.canvas.width = trimWidth;
copy.canvas.height = trimHeight;
copy.putImageData(trimmed, 0, 0);
// open new window with trimmed image:
return copy.canvas;
}
@onassar
Copy link

onassar commented Aug 27, 2018

I'm with @TomFranssen
Anyone have a modification that can trim all consistent pixels? (eg. like Photoshop's trim feature).

@minhnhatspk
Copy link

minhnhatspk commented Dec 26, 2018

Thanks for sharing code.
Your solution and this solution https://github.com/szimek/signature_pad/issues/49#issuecomment-260976909 have the same result.
but I don't know why they don't work with a small canvas.
I receive a cropped base64 string like this data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJoAAACwCAYAAAD3yHdHAAAWqklEQ…R2XRtoY4vDik3+K4DY27CgyngC092SXi3pl3sR9BxnnAL/C1ghAjtx4zZSAAAAAElFTkSuQmCC.
It does not display since it is broken.

@shaangidwani
Copy link

its not working on ipad. can someone help us urgently.

@hangj
Copy link

hangj commented Jun 5, 2019

var trimHeight = bound.bottom - bound.top,
trimWidth = bound.right - bound.left,
SHOULD BE:
var trimHeight = bound.bottom - bound.top + 1,
trimWidth = bound.right - bound.left + 1,

@javix
Copy link

javix commented Nov 4, 2020

I created my own with some optimizations to minimize the number of pixels examined:

https://gist.github.com/timdown/021d9c8f2aabc7092df564996f5afbbf

This function is almost 300% faster.

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