Skip to content

Instantly share code, notes, and snippets.

@paintparty
Created January 28, 2020 17:55
Show Gist options
  • Save paintparty/09a1842f5814e61483a73f305773e8cd to your computer and use it in GitHub Desktop.
Save paintparty/09a1842f5814e61483a73f305773e8cd to your computer and use it in GitHub Desktop.
// c is an object like {:cnvs <cnvs> :ctx <ctx>}
function canvasTrim(c, o={}) {
if(isEmpty(o)){o.top = o.left = o.right = o.bottom = true;}
var w = c.cnvs.width,
h = c.cnvs.height,
ctx = c.ctx,
padding = 2, // Padding around trim
imageData = ctx.getImageData(0, 0, w, h), // Get Pixel Data
alpha = [],
tl = {x: 99999, y: 99999}, // Top left
br = {x: -1, y: -1}, // Bottom right
pix = imageData.data,
xtraHeight = (!o.top && !o.bottom) ? 0 : 1,
xtraWidth = (!o.right && !o.left) ? 0 : 1,
i = 0,
x, y, newWidth, newHeight, crop;
// Loop thru the image data and check alpha for anything
for (i; i < pix.length; i += 4) {
alpha[i / 4] = pix[i + 3];
if (pix[i + 3] > 0) {
x = i / 4 % w;
y = (i / 4 - x) / w;
if (x < tl.x) {tl.x = x;}
if (y < tl.y) {tl.y = y;}
if (x > br.x) {br.x = x;}
if (y > br.y) {br.y = y;}
}
}
// Set w and h for cropped canvas and get image data for crop
// First check for overrides (in case of first and last rows of paragraph)
if (!o.top) {tl.y = 0;}
if (!o.bottom) {br.y = h;}
if (!o.left) {tl.x = 0;}
if (!o.right) {br.x = w;}
newWidth = (br.x - tl.x) + xtraWidth;
newHeight = (br.y - tl.y) + xtraHeight;
//crop = ctx.getImageData(tl.x - padding, tl.y - padding, newWidth + padding, newHeight + padding);
// Resize cnvs
//c.cnvs.width = newWidth + padding;
//c.cnvs.height = newHeight + padding;// if you need all sides
// Clear cnvs
//ctx.clearRect(0, 0, c.cnvs.width, c.cnvs.height);
var newCanvas = new Canvas(newWidth + padding, newHeight + padding);
var newCtx = newCanvas.getContext('2d');
// Composite in cropped data
//ctx.putImageData(crop, -padding / 2, -padding / 2);
newCtx.drawImage(c.cnvs, tl.x, tl.y, (br.x-tl.x), (br.y - tl.y), 0, 0, (br.x-tl.x), (br.y - tl.y));
//return c;
return newCanvas
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment