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 ...

Leave a Reply

Your email address will not be published. Required fields are marked *

skype

Need Coding Help?

Connect Skype

AI

Jobs

Nextjs

Node

Npm

Prisma

React

Remix-run

Shopify App

tailwindcss

Tech

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

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

structure of react project

...

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

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

Prisma config with Mongodb

1-Install the Prisma CLI: 2-Initialize a Prisma pr ...

essential Npm package for developers

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

top
× How can I help you?