Last active
April 19, 2023 20:02
-
-
Save Roy-Ermers/28d439489811ff2021ca8bcca657b564 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default class Color { | |
static fromGrayscale(value: number) { | |
return Math.ceil(value) << 16 | Math.ceil(value) << 8 | Math.ceil(value); | |
} | |
static fromRgb(r: number, g: number, b: number) { | |
return r << 16 | g << 8 | b; | |
} | |
static toRgb(color: number) { | |
return { | |
r: (color >> 16) & 255, | |
g: (color >> 8) & 255, | |
b: color & 255 | |
}; | |
} | |
public get r() { | |
return this._r; | |
} | |
public get g() { | |
return this._g; | |
} | |
public get b() { | |
return this._b; | |
} | |
private _r: number; | |
private _g: number; | |
private _b: number; | |
constructor(r: number); | |
constructor(r: number, g: number, b: number); | |
constructor(r: number, g?: number, b?: number) { | |
if (r !== undefined && g === undefined && b === undefined) { | |
const color = Color.toRgb(r); | |
this._r = color.r; | |
this._g = color.g; | |
this._b = color.b; | |
return; | |
} | |
this._r = r; | |
this._g = g!; | |
this._b = b!; | |
} | |
valueOf() { | |
return this._r << 16 | this._g << 8 | this._b; | |
} | |
[Symbol.toPrimitive]() { | |
return this.valueOf(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default class Gradient { | |
constructor(private a: Color, private b: Color) { } | |
public getColorAt(interpolation: number) { | |
if (interpolation <= 0) | |
return this.a.valueOf(); | |
if (interpolation >= 1) | |
return this.b.valueOf(); | |
const r = this.getIndex(interpolation, this.a.r, this.b.r); | |
const g = this.getIndex(interpolation, this.a.g, this.b.g); | |
const b = this.getIndex(interpolation, this.a.b, this.b.b); | |
return Color.fromRgb(r, g, b); | |
} | |
private getIndex(fraction: number, start: number, end: number) { | |
const lower = Gradient.inverseCompanding(start / 255); | |
const upper = Gradient.inverseCompanding(end / 255); | |
return Gradient.companding((upper - lower) * fraction + lower) * 255; | |
} | |
private static inverseCompanding(val: number) { | |
return (val > 0.04045) ? Math.pow((val + 0.055) / 1.055, 2.4) : val / 12.92; | |
} | |
private static companding(val: number) { | |
return (val > 0.0031308) ? 1.055 * Math.pow(val, 1 / 2.4) - 0.055 : val * 12.92; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment