All files / Rindu/utils getMainColorFromImage.ts

93.75% Statements 30/32
94.44% Branches 17/18
100% Functions 2/2
93.75% Lines 30/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61    44x   44x   6x         6x 6x 6x 6x 1x   5x       5x 5x 5x 5x 5x 5x 5x 2x   3x   5x           5x 5x   5x 2x           2x     3x 2x 2x   1x 1x 1x      
import { Dispatch, SetStateAction } from "react";
 
import { rgbToHex } from "utils";
 
const cache: Record<string, string> = {};
 
export function getMainColorFromImage(
  imageId: string,
  callback: Dispatch<SetStateAction<string>> | ((color: string) => void),
  config?: { dsx: number; dwy: number; dw: number; dh: number }
): void {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  const img = document.querySelector(`#${imageId}`) as HTMLImageElement;
  if (!img || !ctx) {
    return;
  }
  Iif (cache[img.src]) {
    callback(cache[img.src]);
    return;
  }
  const image = new Image();
  image.crossOrigin = "anonymous";
  image.src = img.src;
  image.onload = () => {
    canvas.width = image.width;
    canvas.height = image.height;
    if (config) {
      ctx.drawImage(image, config.dsx, config.dwy, config.dw, config.dh);
    } else {
      ctx.drawImage(image, 0, 0);
    }
    const imageData = ctx.getImageData(
      config?.dsx ?? 0,
      config?.dwy ?? 0,
      canvas.width,
      canvas.height
    ).data;
    const rgb = { r: imageData[0], g: imageData[1], b: imageData[2] };
    const luma = 0.2126 * rgb.r + 0.7152 * rgb.g + 0.0722 * rgb.b;
 
    if ((luma > 220 || luma < 30) && !config) {
      getMainColorFromImage(imageId, callback, {
        dsx: 0,
        dwy: 0,
        dw: 1,
        dh: 1,
      });
      return;
    }
 
    if ((luma > 220 || luma < 30) && config) {
      callback("#7a7a7a");
      return;
    }
    const hex = rgbToHex(rgb);
    cache[img.src] = hex;
    callback(hex);
  };
}