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];


				const lightness = (r + g + b) / (256 * 3);
        
        if (lightness > 0.92) {
	        const percent = (lightness - 0.92) / 0.08;
	        pixels[i + 3] = Math.floor((1 - percent) * 256);
        }
        
    if (r >= 250 && g >= 250 && b >= 250) {

    } 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);

  c.width = trimmedWidth;
  c.height = trimmedHeight;
  ctx.putImageData(imgData, -bounds.left, -bounds.top);
};

const img = new Image();
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');

img.src = 'https://stephenhendricks.me/img/example3.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);
};