Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Created March 17, 2012 06:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathantneal/2055635 to your computer and use it in GitHub Desktop.
Save jonathantneal/2055635 to your computer and use it in GitHub Desktop.
Canvas Prototype: Trim
HTMLCanvasElement.prototype.trim = function () {
var
canvas = this,
width = canvas.width,
height = canvas.height,
pixels = width * height,
context = canvas.getContext('2d'),
imageData = context.getImageData(0, 0, width, height),
canvasPixelArray = imageData.data,
top = height,
right = 0,
bottom = 0,
left = width,
i = 0,
row;
for (; i < pixels; ++i) {
if (canvasPixelArray[i * 4] > 0) {
row = Math.floor(i / height);
top = Math.min(top, row);
right = Math.max(right, i % width);
bottom = Math.max(bottom, row);
left = Math.min(left, i % width);
}
}
canvas.width = right - left;
canvas.height = bottom - top;
context.putImageData(imageData, 0 - left, 0 - top);
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment