Skip to content

Commit 2322bda

Browse files
fix Color.toString() issues: add 'hex' alias and correct 'hsla%' output
1 parent c0513a3 commit 2322bda

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

src/color/p5.Color.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,7 @@ p5.Color = class Color {
374374
* @param {String} [format] how the color string will be formatted.
375375
* Leaving this empty formats the string as rgba(r, g, b, a).
376376
* '#rgb' '#rgba' '#rrggbb' and '#rrggbbaa' format as hexadecimal color codes.
377+
* 'hex' is an alias for '#rrggbb'.
377378
* 'rgb' 'hsb' and 'hsl' return the color formatted in the specified color mode.
378379
* 'rgba' 'hsba' and 'hsla' are the same as above but with alpha channels.
379380
* 'rgb%' 'hsb%' 'hsl%' 'rgba%' 'hsba%' and 'hsla%' format as percentages.
@@ -408,6 +409,7 @@ p5.Color = class Color {
408409
const alpha = f[3]; // String representation uses normalized alpha
409410

410411
switch (format) {
412+
case 'hex':
411413
case '#rrggbb':
412414
return '#'.concat(
413415
a[0] < 16 ? '0'.concat(a[0].toString(16)) : a[0].toString(16),
@@ -552,7 +554,7 @@ p5.Color = class Color {
552554

553555
case 'hsla%':
554556
if (!this.hsla) this.hsla = color_conversion._rgbaToHSLA(this._array);
555-
return 'hsl('.concat(
557+
return 'hsla('.concat(
556558
(100 * this.hsla[0]).toPrecision(3),
557559
'%, ',
558560
(100 * this.hsla[1]).toPrecision(3),

test/unit/color/p5.Color.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -996,5 +996,26 @@ suite('p5.Color', function() {
996996
test('should not mutate color levels', function() {
997997
assert.deepEqual(c.levels, [128, 0, 128, 128]);
998998
});
999+
1000+
test('should format as #rrggbb hex string', function() {
1001+
var testColor = myp5.color(153, 50, 204); // darkorchid
1002+
assert.equal(testColor.toString('#rrggbb'), '#9932cc');
1003+
});
1004+
1005+
test('should format as hex string with "hex" alias', function() {
1006+
var testColor = myp5.color(153, 50, 204); // darkorchid
1007+
assert.equal(testColor.toString('hex'), '#9932cc');
1008+
});
1009+
1010+
test('should format hsla% with correct function name', function() {
1011+
var testColor = myp5.color(128, 0, 128, 128);
1012+
var result = testColor.toString('hsla%');
1013+
assert.include(result, 'hsla(');
1014+
});
1015+
1016+
test('should handle single digit hex values with padding', function() {
1017+
var testColor = myp5.color(10, 5, 15);
1018+
assert.equal(testColor.toString('#rrggbb'), '#0a050f');
1019+
});
9991020
});
10001021
});

0 commit comments

Comments
 (0)