Skip to content

Instantly share code, notes, and snippets.

@rpearce
Created March 31, 2021 14:17
Show Gist options
  • Save rpearce/7806764b7ba2694ba27a849e3178db9e to your computer and use it in GitHub Desktop.
Save rpearce/7806764b7ba2694ba27a849e3178db9e to your computer and use it in GitHub Desktop.
Ligthen Darken Hex Colors
// helper functions are from https://github.com/rpearce/hex
const lightenDarken = (direction, color) => {
const rgb = hexToRgba(color).slice(0, 3)
// algo from https://stackoverflow.com/a/21038522/680394
const rgbAdjusted = direction >= 0
? rgb.map(x => (1 - direction) * x + direction * 255)
: rgb.map(x => (1 + direction) * x)
return rgbaToHex(rgbAdjusted).slice(0, 7)
}
const hexToRgba = x => {
const hex = parse(x)
const head = hex.slice(0, 6)
const tail = hex.slice(6)
const n = parseInt(head, 16)
return [(n >> 16) & 0xff, (n >> 8) & 0xff, (n >> 0) & 0xff, getAlpha(tail)]
}
const rgbaToHex = ([r = 0, g = 0, b = 0, a = 1] = []) => {
const rgbN = (1 << 24) | (r << 16) | (g << 8) | b
const hex = rgbN.toString(16).slice(1)
const alpha = (a * 255)
.toString(16)
.padStart(2, '0')
.slice(0, 2)
return `#${hex}${alpha}`
}
const parse = (x = '') => {
const hex = x.replace(/^#/, '')
const len = hex.length
return len === 3 || len === 4 ? repeat(hex) : hex
}
const repeat = x =>
x.split('').map(y => y + y).join('')
const getAlpha = x =>
x ? parseFloat((parseInt(x, 16) / 0xff).toFixed(2)) : 1
lightenDarken(0.9, '#DF3894') // "#fbebf4"
@rpearce
Copy link
Author

rpearce commented Mar 31, 2021

Alternative rgbaToHex function that may yield a slightly different result (and doesn't use alpha):

const rgbToHex = (rgb = []) =>
  '#' + rgb.map(x =>
    Math
      .min(255, Math.max(0, Math.round(x)))
      .toString(16)
      .padStart(2, '0')
  ).join('')

rgbToHex([223,56,148]) // "#df3894"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment