Standardize css.toColor output to #rrggbb[aa]
This will help reduce the chance of runtime exceptions that would break the render loop.
This commit is contained in:
+21
-31
@@ -96,25 +96,19 @@ export namespace css {
|
||||
export function toColor(css: string): IColor {
|
||||
if (css.match(/#[0-9a-f]{3,8}/i)) {
|
||||
switch (css.length) {
|
||||
case 4: // #rgb
|
||||
return {
|
||||
css,
|
||||
rgba: channels.toRgba(
|
||||
parseInt(css.slice(1, 2).repeat(2), 16),
|
||||
parseInt(css.slice(2, 3).repeat(2), 16),
|
||||
parseInt(css.slice(3, 4).repeat(2), 16)
|
||||
)
|
||||
};
|
||||
case 5: // #rgba
|
||||
return {
|
||||
css,
|
||||
rgba: channels.toRgba(
|
||||
parseInt(css.slice(1, 2).repeat(2), 16),
|
||||
parseInt(css.slice(2, 3).repeat(2), 16),
|
||||
parseInt(css.slice(3, 4).repeat(2), 16),
|
||||
parseInt(css.slice(4, 5).repeat(2), 16)
|
||||
)
|
||||
};
|
||||
case 4: { // #rgb
|
||||
const r = parseInt(css.slice(1, 2).repeat(2), 16);
|
||||
const g = parseInt(css.slice(2, 3).repeat(2), 16);
|
||||
const b = parseInt(css.slice(3, 4).repeat(2), 16);
|
||||
return rgba.toColor(r, g, b);
|
||||
}
|
||||
case 5: { // #rgba
|
||||
const r = parseInt(css.slice(1, 2).repeat(2), 16);
|
||||
const g = parseInt(css.slice(2, 3).repeat(2), 16);
|
||||
const b = parseInt(css.slice(3, 4).repeat(2), 16);
|
||||
const a = parseInt(css.slice(4, 5).repeat(2), 16);
|
||||
return rgba.toColor(r, g, b, a);
|
||||
}
|
||||
case 7: // #rrggbb
|
||||
return {
|
||||
css,
|
||||
@@ -129,15 +123,11 @@ export namespace css {
|
||||
}
|
||||
const rgbaMatch = css.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);
|
||||
if (rgbaMatch) { // rgb() or rgba()
|
||||
return {
|
||||
css,
|
||||
rgba: channels.toRgba(
|
||||
parseInt(rgbaMatch[1]), // r
|
||||
parseInt(rgbaMatch[2]), // g
|
||||
parseInt(rgbaMatch[3]), // b
|
||||
Math.round((rgbaMatch[5] === undefined ? 1 : parseFloat(rgbaMatch[5])) * 0xFF) // a?
|
||||
)
|
||||
};
|
||||
const r = parseInt(rgbaMatch[1]);
|
||||
const g = parseInt(rgbaMatch[2]);
|
||||
const b = parseInt(rgbaMatch[3]);
|
||||
const a = Math.round((rgbaMatch[5] === undefined ? 1 : parseFloat(rgbaMatch[5])) * 0xFF);
|
||||
return rgba.toColor(r, g, b, a);
|
||||
}
|
||||
throw new Error('css.toColor: Unsupported css format');
|
||||
}
|
||||
@@ -268,10 +258,10 @@ export namespace rgba {
|
||||
return [(value >> 24) & 0xFF, (value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF];
|
||||
}
|
||||
|
||||
export function toColor(r: number, g: number, b: number): IColor {
|
||||
export function toColor(r: number, g: number, b: number, a?: number): IColor {
|
||||
return {
|
||||
css: channels.toCss(r, g, b),
|
||||
rgba: channels.toRgba(r, g, b)
|
||||
css: channels.toCss(r, g, b, a),
|
||||
rgba: channels.toRgba(r, g, b, a)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user