Skip to content

Instantly share code, notes, and snippets.

@carlmw
Created February 8, 2017 11:27
Show Gist options
  • Save carlmw/a0130c6e45c4935870bf316fbb38739c to your computer and use it in GitHub Desktop.
Save carlmw/a0130c6e45c4935870bf316fbb38739c to your computer and use it in GitHub Desktop.
Darken/lighten a hex colour
function clamp(val, min, max) {
return Math.max(min, Math.min(max, val));
}
function colorShift(hex, amount) {
const colour = parseInt(hex.slice(1), 16);
let r = (colour >> 16) + amount;
let g = (colour & 0x0000FF) + amount;
let b = ((colour >> 8) & 0x00FF) + amount;
r = clamp(r, 0, 255);
g = clamp(g, 0, 255);
b = clamp(b, 0, 255);
const out = `000000${(g | (b << 8) | (r << 16)).toString(16)}`.substr(-6);
return `#${out}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment