Skip to content

Instantly share code, notes, and snippets.

@demouth
Last active August 9, 2018 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save demouth/f085f57586ab67dc419ccbfc3fb1de76 to your computer and use it in GitHub Desktop.
Save demouth/f085f57586ab67dc419ccbfc3fb1de76 to your computer and use it in GitHub Desktop.
/*
* Porting https://gist.github.com/demouth/1986726
*
* Example
* ```
* //Example 1
* let c = new Color();
* c.rgb(250,10,10).v(c.v() * 0.8);
*
* //Example 2
*
* let c = new Color();
* c.hsv(0,0.2,0.9).h(Date.now()*0.1);
* context2d.fillStyle = c.rgb();
* ```
*/
class Color{
constructor(){
this._r = 0;
this._g = 0;
this._b = 0;
}
rgb(r,g,b){
if (!r) {
return '#'+('000000'+(this._r << 16 | this._g << 8 | this._b).toString(16)).slice(-6);
}
this._r = r;
this._g = g;
this._b = b;
this.updateHSV();
return this;
}
hsv(h,s,v){
this._h = h;
this._s = s;
this._v = v;
this.updateRGB();
return this;
}
h(p){
if (!p) return this._h;
this._h = p%360;
this.updateRGB();
return this;
}
s(p){
if (!p) return this._s;
this._s = p;
this.updateRGB();
return this;
}
v(p){
if (!p) return this._v;
this._v = p;
this.updateRGB();
return this;
}
updateHSV(){
let hsv = [0, 0, 0];
const r = this._r / 255;
const g = this._g / 255;
const b = this._b / 255;
const max = Math.max(r,g,b);
const min = Math.min(r,g,b);
if(max !== 0){
hsv[1] = (max - min) / max;
if(max == r){
hsv[0] = 60 * (g - b) / (max-min);
}else if(max === g){
hsv[0] = 60 * (b - r) / (max - min) + 120;
}else{
hsv[0] = 60 * (r - g) / (max - min) + 240;
}
while (hsv[0] < 0){
hsv[0] += 360;
}
}
hsv[2] = max;
this._h = hsv[0];
this._s = hsv[1];
this._v = hsv[2];
return this;
}
updateRGB(){
const h = this._h;
const s = this._s;
const v = this._v;
if(s == 0) {
this._r = ~~(v * 255);
this._g = ~~(v * 255);
this._b = ~~(v * 255);
}else{
const hi = (h/60)>>0;
const f = (h/60 - hi);
const p = v*(1 - s);
const q = v*(1 - f*s);
const t = v*(1-(1-f)*s);
if(hi==0){
this._r = ~~(v * 255);
this._g = ~~(t * 255);
this._b = ~~(p * 255);
}else if(hi==1){
this._r = ~~(q * 255);
this._g = ~~(v * 255);
this._b = ~~(p * 255);
}else if(hi==2){
this._r = ~~(p * 255);
this._g = ~~(v * 255);
this._b = ~~(t * 255);
}else if(hi==3){
this._r = ~~(p * 255);
this._g = ~~(q * 255);
this._b = ~~(v * 255);
}else if(hi==4){
this._r = ~~(t * 255);
this._g = ~~(p * 255);
this._b = ~~(v * 255);
}else if(hi==5){
this._r = ~~(v * 255);
this._g = ~~(p * 255);
this._b = ~~(q * 255);
}
}
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment