diff --git a/src/color/p5.Color.js b/src/color/p5.Color.js index 91b96f0059..faecf0a7d6 100644 --- a/src/color/p5.Color.js +++ b/src/color/p5.Color.js @@ -45,7 +45,7 @@ const map = (n, start1, stop1, start2, stop2, clamp) => { }; const toHexComponent = v => { - const vInt = ~~(v * 255); + const vInt = Math.round(v * 255); const hex = vInt.toString(16); if (hex.length < 2) { return '0' + hex; diff --git a/test/unit/color/p5.Color.js b/test/unit/color/p5.Color.js index 5021a53f18..50b3078148 100644 --- a/test/unit/color/p5.Color.js +++ b/test/unit/color/p5.Color.js @@ -850,5 +850,27 @@ suite('p5.Color', function () { assert.equal(result, '#9932cc'); }); }); + + suite('default format with fractional channel values', function () { + test('should round fractional channel values matching #rrggbb format', function () { + mockP5Prototype.colorMode(mockP5Prototype.RGB, 100); + const c = mockP5Prototype.color(50, 0, 0); + assert.equal(c.toString(), '#800000'); + assert.equal(c.toString(), c.toString('#rrggbb')); + }); + + test('should round fractional channel in 255 range', function () { + mockP5Prototype.colorMode(mockP5Prototype.RGB, 255); + const c = mockP5Prototype.color(127.5, 0, 0); + assert.equal(c.toString(), '#800000'); + assert.equal(c.toString(), c.toString('#rrggbb')); + }); + + test('should round fractional alpha byte', function () { + mockP5Prototype.colorMode(mockP5Prototype.RGB, 255); + const c = mockP5Prototype.color(255, 0, 102, 127.5); + assert.equal(c.toString(), '#ff006680'); + }); + }); }); });