Skip to content

Instantly share code, notes, and snippets.

@mrclay
Created June 5, 2020 13:57
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 mrclay/c7222ce81601ffb1fbbfefd76741dff5 to your computer and use it in GitHub Desktop.
Save mrclay/c7222ce81601ffb1fbbfefd76741dff5 to your computer and use it in GitHub Desktop.
type RGB = [number, number, number];
export function parseRgb(color: RGB | string): RGB {
if (Array.isArray(color)) {
return color;
}
let c = color;
let m;
if (
(m = c.match(/^rgb\s*\(\s*([\d%.]+)\s*,\s*([\d%.]+)\s*,\s*([\d%.]+)\s*\)/))
) {
// rgb(a,b,c)
m.shift();
for (let i = 0; i < 3; i++) {
m[i] *= /%/.test(m[i]) ? 100.0 : 1.0;
}
return m;
}
if ((m = c.match(/^#(.)(.)(.)$/))) {
// convert #abc to #aabbcc
c = '#' + m[1] + m[1] + m[2] + m[2] + m[3] + m[3];
}
if ((m = c.match(/^#(..)(..)(..)$/))) {
// #abcdef
m.shift();
for (let i = 0; i < 3; i++) {
m[i] = parseInt(m[i], 16);
}
return m;
}
throw new Error(`${color} not parsable as color`);
}
export function cssColorBetween(
c1: RGB | string,
c2: RGB | string,
distance = 0.5, // halfway
): string {
const rgb1 = parseRgb(c1);
const rgb2 = parseRgb(c2);
return cssColor([
Math.round(rgb1[0] + (rgb2[0] - rgb1[0]) * distance),
Math.round(rgb1[1] + (rgb2[1] - rgb1[1]) * distance),
Math.round(rgb1[2] + (rgb2[2] - rgb1[2]) * distance),
]);
}
export function cssColor(rgb: RGB) {
return `rgb(${rgb.join(', ')})`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment