diff --git a/CHANGELOG.md b/CHANGELOG.md index 6288a9ac9..2227735e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -85,6 +85,7 @@ will be positioned with the top left of the graphic at the actor's position. - Fixed issue where Firefox on Linux would throw an error when using custom Materials due to unused attributes caused by glsl compiler optimization. - Fixed issue where start transition did not work properly if deferred - Fixed issue where transitions did not cover the whole screen if camera was zoomed +- Fixed issue where `Color.toHex()` produced invalid strings if the channel values are negative or fractional, or if the alpha channel was different than 1 ### Updates diff --git a/src/engine/Color.ts b/src/engine/Color.ts index 65a370049..6c44e81b1 100644 --- a/src/engine/Color.ts +++ b/src/engine/Color.ts @@ -222,7 +222,8 @@ export class Color { * @see https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb */ private _componentToHex(c: number) { - const hex = c.toString(16); + // Handle negative and fractional numbers + const hex = Math.max(Math.round(c), 0).toString(16); return hex.length === 1 ? '0' + hex : hex; } @@ -230,7 +231,11 @@ export class Color { * Return Hex representation of a color. */ public toHex() { - return '#' + this._componentToHex(this.r) + this._componentToHex(this.g) + this._componentToHex(this.b); + let hexRepresentation = '#' + this._componentToHex(this.r) + this._componentToHex(this.g) + this._componentToHex(this.b); + if (this.a !== 1) { + hexRepresentation += this._componentToHex(this.a * 255); + } + return hexRepresentation; } /** @@ -413,7 +418,7 @@ export class Color { * http://axonflux.com/handy-rgb-to-hsl-and-rgb-to-hsv-color-model-c */ class HSLColor { - constructor(public h: number, public s: number, public l: number, public a: number) {} + constructor(public h: number, public s: number, public l: number, public a: number) { } public static hue2rgb(p: number, q: number, t: number): number { if (t < 0) { diff --git a/src/spec/ColorSpec.ts b/src/spec/ColorSpec.ts index e31cda815..6c2848535 100644 --- a/src/spec/ColorSpec.ts +++ b/src/spec/ColorSpec.ts @@ -108,6 +108,17 @@ describe('A color', () => { expect(color.a).toBe(31 / 255); }); + it('generate valid hex representation', () => { + color = ex.Color.White; + expect(color.toHex()).toBe('#ffffff'); + color = ex.Color.Green; + expect(color.toHex()).toBe('#00ff00'); + color = ex.Color.fromRGB(17,17,17,0.1); + expect(color.toHex()).toBe('#1111111a'); + color = ex.Color.fromRGB(16.9, 16.9, 16.9); + expect(color.toHex()).toBe('#111111'); + }); + it('can be darkened', () => { color = ex.Color.White.clone(); color = color.darken();