JSFiddle - React, Tailwind, and code Playground
by brigand
CSS
body {
background-color: #000;
}
JavaScript
const getBounds = (c) => {
};
const trimCanvas = (c) => {
const ctx = c.getContext('2d');
let imgData = ctx.getImageData(0, 0, c.width, c.height);
let pixels = imgData.data;
const bounds = {
top: null,
right: null,
bottom: null,
left: null
};
for (let i = 0, j = pixels.length; i < j; i += 4) {
const r = pixels[i];
const g = pixels[i + 1];
const b = pixels[i + 2];
if (r >= 250 && g >= 250 && b >= 250) {
pixels[i] = 0;
pixels[i + 1] = 0;
pixels[i + 2] = 0;
pixels[i + 3] = 0;
} else {
let x = (i / 4) % c.width;
let y = ~~((i / 4) / c.width);
if (bounds.top === null) {
bounds.top = y;
}
if (bounds.right === null || bounds.right < x) {
bounds.right = x;
}
if (bounds.bottom === null || bounds.bottom < y) {
bounds.bottom = y;
}
if (bounds.left === null || x < bounds.left) {
bounds.left = x;
}
}
}
const trimmedHeight = bounds.bottom - bounds.top;
const trimmedWidth = bounds.right - bounds.left;
console.log(trimmedWidth, trimmedHeight);
ctx.putImageData(imgData, 0, 0);
const trimmed = ctx.getImageData(bounds.left, bounds.top, trimmedWidth, trimmedHeight);
c.width = trimmedWidth;
c.height = trimmedHeight;
ctx.putImageData(trimmed, 0, 0);
};
const img = new Image();
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
img.src = 'https://stephenhendricks.me/img/example.jfif';
img.crossOrigin = 'Anonymous';
img.onload = function () {
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
ctx.drawImage(this, 0, 0);
document.body.appendChild(canvas);
trimCanvas(canvas);
};