UNPKG

@aurigma/design-atoms-model

Version:

Design Atoms is a part of Customer's Canvas SDK which allows for manipulating individual design elements through your code.

112 lines 3.44 kB
import { RgbColor } from "./RgbColor"; import { Clamp } from "../Math"; import { validateComponent } from "./ValidationUtils"; export class HsbColor { constructor(h, s, b, alpha) { this._h = validateComponent(h, 0, 1); this._s = validateComponent(s, 0, 1); this._b = validateComponent(b, 0, 1); this._alpha = validateComponent(alpha); } /** * Hue in range [0, 1] */ get h() { return this._h; } /** * Saturation in range [0, 1] */ get s() { return this._s; } /** * Brightness in range [0, 1] */ get b() { return this._b; } /** * Alpha in range [0, 255] */ get alpha() { return this._alpha; } static fromRgb(rgbColor) { const r = rgbColor.r / 255; const g = rgbColor.g / 255; const b = rgbColor.b / 255; const max = Math.max(r, g, b); const min = Math.min(r, g, b); let hue = max; const brightness = max; const d = max - min; const saturation = max === 0 ? 0 : d / max; if (max === min) { hue = 0; // achromatic } else { switch (max) { case r: hue = (g - b) / d + (g < b ? 6 : 0); break; case g: hue = (b - r) / d + 2; break; case b: hue = (r - g) / d + 4; break; } hue /= 6 % 360; } return new HsbColor(hue, saturation, brightness, rgbColor.alpha); } toRgb() { const h = this.h * 6, i = Math.floor(h), f = h - i, p = this.b * (1 - this.s), q = this.b * (1 - f * this.s), t = this.b * (1 - (1 - f) * this.s), mod = i % 6, r = Math.round([this.b, q, p, p, t, this.b][mod] * 255), g = Math.round([t, this.b, this.b, q, p, p][mod] * 255), b = Math.round([p, p, t, this.b, this.b, q][mod] * 255); return new RgbColor(r, g, b, this.alpha); } clone() { return new HsbColor(this.h, this.s, this.b, this.alpha); } decreaseHue(value) { const result = this.clone(); result._h = Clamp(0, result.h - value, 1); return result; } increaseHue(value) { const result = this.clone(); result._h = Clamp(0, result.h + value, 1); return result; } desaturate(value) { const result = this.clone(); result._s = Clamp(0, result.s - value, 1); return result; } saturate(value) { const result = this.clone(); result._s = Clamp(0, result.s + value, 1); return result; } darken(value) { const result = this.clone(); result._b = Clamp(0, result.b - value, 1); return result; } lighten(value) { const result = this.clone(); result._b = Clamp(0, result.b + value, 1); return result; } decreaseAlpha(value) { const result = this.clone(); result._alpha = Clamp(0, result.alpha - value, 255); return result; } increaseAlpha(value) { const result = this.clone(); result._alpha = Clamp(0, result.alpha + value, 255); return result; } } //# sourceMappingURL=HsbColor.js.map