Skip to content

Instantly share code, notes, and snippets.

@kazuma0129
Forked from xenozauros/hex2hsl.js
Last active May 4, 2020 05:27
Show Gist options
  • Save kazuma0129/279d0da227c5e4ba3dba20bd360b1cb5 to your computer and use it in GitHub Desktop.
Save kazuma0129/279d0da227c5e4ba3dba20bd360b1cb5 to your computer and use it in GitHub Desktop.
Javascript: HEX to RGB to HSL
fucntion hexToHSL(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
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)
let h = 0
let s = 0
const l = (max + min) / 2
if (max === min) {
h = s = 0 // achromatic
} else {
const d = max - min
s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0)
break
case g:
h = (b - r) / d + 2
break
case b:
h = (r - g) / d + 4
break
}
h /= 6
}
const HSL = { h: h * 360, s: s * 100, l: l * 100 }
return HSL
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment