Skip to content

Instantly share code, notes, and snippets.

@mwmwmw
Created December 16, 2017 08:04
Show Gist options
  • Save mwmwmw/8432693f52434997f1fe52694a8ec270 to your computer and use it in GitHub Desktop.
Save mwmwmw/8432693f52434997f1fe52694a8ec270 to your computer and use it in GitHub Desktop.
Just some color conversion stuff
const HEX = /#([0-9ABCDEF]{2})([0-9ABCDEF]{2})([0-9ABCDEF]{2})/;
const VEC3 = /vec3\s?\(([0-9.]*),\s?([0-9.]*),\s?([0-9.]*)\)/;
const DEFAULT_VALUE = 0;
class Color {
static hex2vec3(hex) {
let matches = Color.parseHex(hex);
return Color.vec3(matches, 256);
}
static hex2rgb(hex) {
let matches = Color.parseHex(hex);
return Color.rgb(matches);
}
static vec32rgb(vec3) {
let matches = Color.parseVec3(vec3);
return Color.rgb(matches, 256);
}
static parseHex(string) {
let matches = HEX.exec(string);
if (matches[1] && matches[2] && matches[3]) {
return [
parseInt(matches[1], 16),
parseInt(matches[2], 16),
parseInt(matches[3], 16)
];
} else {
return [DEFAULT_VALUE, DEFAULT_VALUE, DEFAULT_VALUE];
}
}
static parseVec3(string) {
let matches = VEC3.exec(string);
if (matches[1] && matches[2] && matches[3]) {
return [
parseFloat(matches[1], 10),
parseFloat(matches[2], 10),
parseFloat(matches[3], 10)
];
} else {
return [DEFAULT_VALUE, DEFAULT_VALUE, DEFAULT_VALUE];
}
}
static vec3(m, divisor = 1) {
return `vec3(${m[0] / divisor}, ${m[1] / divisor}, ${m[2] / divisor})`;
}
static rgb(m, scalar = 1) {
return `rgb(${Math.abs(m[0] * scalar)}, ${Math.abs(
m[1] * scalar
)}, ${Math.abs(m[2] * scalar)})`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment