Convert Hex to hsb using js

export const hexToHsb = (hex: string) => {
  // Remove the "#" symbol if present
  hex = hex.replace("#", "");

  // Convert HEX to RGB
  const r = parseInt(hex.substring(0, 2), 16) / 255;
  const g = parseInt(hex.substring(2, 4), 16) / 255;
  const b = parseInt(hex.substring(4, 6), 16) / 255;

  // Calculate the maximum and minimum RGB values
  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);

  // Calculate brightness (V)
  const brightness = max;

  // Calculate saturation (S)
  const saturation = max === 0 ? 0 : (max - min) / max;

  // Calculate hue (H)
  let hue;
  if (max === min) {
    hue = 0; // No saturation, so hue is undefined
  } else {
    if (max === r) {
      hue = (g - b) / (max - min);
    } else if (max === g) {
      hue = 2 + (b - r) / (max - min);
    } else {
      hue = 4 + (r - g) / (max - min);
    }
    hue *= 60;
    if (hue < 0) {
      hue += 360;
    }
  }

  // Round HSB values to two decimal places
  const roundedHue = Math.round(hue * 100) / 100;
  const roundedSaturation = Math.round(saturation * 100) / 100;
  const roundedBrightness = Math.round(brightness * 100) / 100;

  return {
    hue: roundedHue,
    saturation: roundedSaturation,
    brightness: roundedBrightness,
  };
};

Next Code

Websites to Find Best Remote Jobs

1. LinkedIn2. Remote.co3. We Work Remotely4. Worki ...

skype

Need Coding Help?

Connect Skype

AI

DATABASE

Jobs

Nextjs

Node

Npm

PHP

Prisma

React

Remix-run

Shopify App

Shopify theme

tailwindcss

Tech

VPS

Woocommerce

WordPress

essential Npm package for developers

Drag and drop image upload Use of the Npm package ...

18 Important HTTP Status Codes You Must Know 🔥

– 200 OK: Request succeeded– 201 Creat ...

How to Setup React and Tailwind CSS with Vite in a Project

Tailwind CSS is a popular CSS framework, and React ...

Shopify Cli

Shopify.app.toml scope or config update Shopify pa ...

Revolutionize Your Shopify App Development with Cloudflared Tunnel: A Game-Changer for Seamless and Secure Connectivity!

Setting up Cloudflare Tunnel Note that while it’ ...

top