Optimize color extraction for pre-parsed values, update d.ts types.

This commit is contained in:
Mikael Sand
2019-01-31 17:21:05 +02:00
parent f0211208c5
commit f8e329c956
4 changed files with 62 additions and 33 deletions
+3 -3
View File
@@ -18,9 +18,9 @@ export default function extractBrush(colorOrBrush) {
} else {
// solid color
const color = extractColor(colorOrBrush);
const r = color[0] / 255;
const g = color[1] / 255;
const b = color[2] / 255;
const r = color[0];
const g = color[1];
const b = color[2];
const a = color[3];
return [0, r, g, b, a === undefined ? 1 : a];
}
+19 -10
View File
@@ -1,4 +1,4 @@
const colorNames = {
export const colorNames = {
aliceblue: [240, 248, 255],
antiquewhite: [250, 235, 215],
aqua: [0, 255, 255],
@@ -148,6 +148,16 @@ const colorNames = {
yellow: [255, 255, 0],
yellowgreen: [154, 205, 50],
};
for (const name in colorNames) {
if (colorNames.hasOwnProperty(name)) {
const color = colorNames[name];
for (let i = 0; i < 3; i++) {
color[i] = color[i] / 255;
}
Object.freeze(color);
}
}
Object.freeze(colorNames);
function hslToRgb(hsl) {
const h = hsl[0] / 360;
@@ -192,7 +202,7 @@ function hslToRgb(hsl) {
val = t1;
}
rgb[i] = val * 255;
rgb[i] = val;
}
return rgb;
@@ -262,7 +272,7 @@ function hwbToRgb(hwb) {
break;
}
return [r * 255, g * 255, b * 255];
return [r, g, b];
}
function clamp(num, min, max) {
@@ -288,7 +298,7 @@ function rgbFromString(string) {
for (i = 0; i < 3; i++) {
// https://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/19
const i2 = i * 2;
rgb[i] = parseInt(match.slice(i2, i2 + 2), 16);
rgb[i] = parseInt(match.slice(i2, i2 + 2), 16) / 255;
}
if (hexAlpha) {
@@ -299,7 +309,7 @@ function rgbFromString(string) {
hexAlpha = match[3];
for (i = 0; i < 3; i++) {
rgb[i] = parseInt(match[i] + match[i], 16);
rgb[i] = parseInt(match[i] + match[i], 16) / 255;
}
if (hexAlpha) {
@@ -308,7 +318,7 @@ function rgbFromString(string) {
}
} else if ((match = string.match(rgba))) {
for (i = 0; i < 3; i++) {
rgb[i] = parseInt(match[i + 1], 0);
rgb[i] = parseInt(match[i + 1], 0) / 255;
}
if (match[4]) {
@@ -316,7 +326,7 @@ function rgbFromString(string) {
}
} else if ((match = string.match(per))) {
for (i = 0; i < 3; i++) {
rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
rgb[i] = parseFloat(match[i + 1]) / 100;
}
if (match[4]) {
@@ -340,10 +350,9 @@ function rgbFromString(string) {
return null;
}
for (i = 0; i < 3; i++) {
rgb[i] = clamp(rgb[i], 0, 255);
for (i = 0; i < 4; i++) {
rgb[i] = clamp(rgb[i], 0, 1);
}
rgb[3] = clamp(rgb[3], 0, 1);
return rgb;
}
+3 -3
View File
@@ -52,9 +52,9 @@ export default function extractGradient(props, parent) {
console.warn(`"${stopColor}" is not a valid color`);
continue;
}
const r = color[0] / 255;
const g = color[1] / 255;
const b = color[2] / 255;
const r = color[0];
const g = color[1];
const b = color[2];
const a = extractOpacity(stopOpacity);
stops.push([offsetNumber, r, g, b, a]);
}