Skip to content

Commit e909e6b

Browse files
committed
Fix an issue with normalizing RGBA values
1 parent 602f750 commit e909e6b

3 files changed

Lines changed: 29 additions & 12 deletions

File tree

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
## Next
22

3+
## v0.18.2
4+
5+
- Fix an issue with normalizing RGBA values
6+
37
## v0.18.1
48

59
- Rename `showRecticle` to `showReticle` and `recticleColor` to `reticleColor` (#47)

src/utils.js

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -303,25 +303,38 @@ export const normNumArray = (a) =>
303303
* normalized to `[0,1]`.
304304
* @return {array} Quadruple defining an RGBA color.
305305
*/
306-
export const toRgba = (color, isNormalize) => {
306+
export const toRgba = (color, shouldNormalize) => {
307307
if (isRgba(color)) {
308-
const base = 255 ** !isNormalize;
309-
return isNormalize && !isNormFloatArray(color)
310-
? color.map((x) => x / 255)
311-
: normNumArray(color).map((x) => x * base);
308+
const isNormalized = isNormFloatArray(color);
309+
if (
310+
(shouldNormalize && isNormalized) ||
311+
(!shouldNormalize && !isNormalized)
312+
)
313+
return color;
314+
if (shouldNormalize && !isNormalized) return color.map((x) => x / 255);
315+
return color.map((x) => x * 255);
312316
}
313317

314318
if (isRgb(color)) {
315-
const base = 255 ** !isNormalize;
316-
return [...normNumArray(color).map((x) => Math.round(x * base)), base];
319+
const base = 255 ** !shouldNormalize;
320+
const isNormalized = isNormFloatArray(color);
321+
322+
if (
323+
(shouldNormalize && isNormalized) ||
324+
(!shouldNormalize && !isNormalized)
325+
)
326+
return [...color, base];
327+
if (shouldNormalize && !isNormalized)
328+
return [...color.map((x) => x / 255), base];
329+
return [...color.map((x) => x * 255), base];
317330
}
318331

319-
if (isHex(color)) return hexToRgba(color, isNormalize);
332+
if (isHex(color)) return hexToRgba(color, shouldNormalize);
320333

321334
console.warn(
322335
'Only HEX, RGB, and RGBA are handled by this function. Returning white instead.'
323336
);
324-
return isNormalize ? [1, 1, 1, 1] : [255, 255, 255, 255];
337+
return shouldNormalize ? [1, 1, 1, 1] : [255, 255, 255, 255];
325338
};
326339

327340
/**

tests/index.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1784,8 +1784,8 @@ test('toRgba()', async (t) => {
17841784
);
17851785

17861786
t.equal(
1787-
toRgba([1, 0, 0, 0.6], true),
1788-
[1, 0, 0, 0.6],
1789-
'should convert normalized RGBA to normalized RGBA'
1787+
toRgba([0, 0, 0, 0.1], true),
1788+
[0, 0, 0, 0.1],
1789+
'should leave normalized RGBA unchanged'
17901790
);
17911791
});

0 commit comments

Comments
 (0)