Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/wojtekmaj/color-utils. A collection of color-related utilities.
color utils
Something went wrong. Try again.
1.0 kB · 48 lines
TypeScript
at lab
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import type { HashHexString, NumberFrom0To1, NumberFrom0To255, RgbaString, RgbObject, RgbString,} from './types.js';
function numberColorToHex(color: NumberFrom0To255): string { return `0${Number(color).toString(16)}`.slice(-2);}
function numberAlphaToHex(color: NumberFrom0To1): string { return numberColorToHex(Math.round(Number(color) * 255));}
export function objectToHex(rgbObject?: RgbObject): HashHexString { if (!rgbObject) { throw new Error('rgbObject is required'); }
const { r, g, b, a } = rgbObject;
const rgbHex = [r, g, b].map(numberColorToHex).join('');
if (a !== undefined && a !== 1) { return `#${rgbHex}${numberAlphaToHex(a)}`; }
return `#${rgbHex}`;}
export function objectToRgb(rgbObject?: RgbObject | null): RgbString | RgbaString { if (!rgbObject) { throw new Error('rgbObject is required'); }
const { r, g, b, a } = rgbObject;
const rgb = [r, g, b].join(' ');
if (a !== undefined && a !== 1) { return `rgb(${rgb} / ${a})`; }
return `rgb(${rgb})`;}