Skip to content

Instantly share code, notes, and snippets.

@jhurliman
Created October 24, 2020 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhurliman/d56bfa7911e116002861ab5e7c80954d to your computer and use it in GitHub Desktop.
Save jhurliman/d56bfa7911e116002861ab5e7c80954d to your computer and use it in GitHub Desktop.
TypeScript methods for color conversion
export type HSL = [number, number, number]
export function HexToHSL(hex: string): HSL | undefined {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
if (!result) return undefined
const r = parseInt(result[1], 16) / 255
const g = parseInt(result[2], 16) / 255
const b = parseInt(result[3], 16) / 255
const max = Math.max(r, g, b)
const min = Math.min(r, g, b)
const l = (max + min) / 2
if (max === min) return [0, 0, l] // achromatic
const d = max - min
const s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
let h
if (max === r) h = (g - b) / d + (g < b ? 6 : 0)
else if (max === g) h = (b - r) / d + 2
else h = (r - g) / d + 4
h /= 6
return [h, s, l]
}
export function HSLToString(hsl: HSL): string {
let [h, s, l] = hsl
h = Math.round(h * 360)
s = Math.round(s * 100)
l = Math.round(l * 100)
return `hsl(${h}, ${s}%, ${l}%)`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment