Skip to content

Instantly share code, notes, and snippets.

@j1ng3r
Last active March 24, 2016 15:56
Show Gist options
  • Save j1ng3r/a1cbdd2acee1b0b318d1 to your computer and use it in GitHub Desktop.
Save j1ng3r/a1cbdd2acee1b0b318d1 to your computer and use it in GitHub Desktop.
function Color(...a){
while(a.length&&typeof a[a.length-1]=='undefined')a.pop();
this.r=0;
this.g=0;
this.b=0;
this.a=0;
if(a.length){
if(typeof a[0]=='string'){
a=a[0].toLowerCase();
if(a[0]=='#')switch((a=a.substr(1)).length){
case 1:
this.set(new Color('#'+a+a));
break;
case 2:
this.set(new Color('#'+a+a+a));
break;
case 3:
this.set(new Color('#'+a[0]+a[0]+a[1]+a[1]+a[2]+a[2]));
break;
case 4:
this.set(new Color('#'+a+a));
break;
case 6:
this.set(new Color('#'+a+'00'));
break;
case 8:
var b = [];
for(var i of a)b.push(Color.hex.indexOf(i));
this.r=b[0]*16+b[1];
this.g=b[2]*16+b[3];
this.b=b[4]*16+b[5];
this.a=b[6]*16+b[7];
break;
default:console.error('Bad string passed in Color');
} else if(a.substr(0,3)=='rgb'){
var b = parseFloat,c=a[3]=='a';
a=a.split('(')[1].split(',');
this.r=b(a[0]);
this.g=b(a[1]);
this.b=b(a[2]);
if(c)this.a=b(a[3]);
} else console.error('Bad string passed in Color');
} else if(typeof a[0]=='object'){
a=a[0];
if(a.constructor==Array)this.set(new Color(a[0],a[1],a[2],a[3]));
else if(a.constructor==Color)this.set(a.r,a.g,a.b,a.a);
} else if(+a[0]==a[0]){
this.r=+a[0]||0;
this.g=+a[1]||0;
this.b=+a[2]||0;
this.a=+a[3]||0;
} else {
console.error('Bad arguments passed in Color');
}
}
}
Color.prototype.blend=function blend(a,b,c,d){
a=new Color(a,b,c,d);
return new Color((this.r+a.r)/2,(this.g+a.g)/2,(this.b+a.b)/2,(this.a+a.a)/2);
}
Color.prototype.set=function set(a){
this.r=a.r;
this.g=a.g;
this.b=a.b;
this.a=a.a;
}
Color.prototype.get=function get(){
return['rbga('+this.r,this.g,this.b,this.a/255+')'].join(',');
}
Color.hex='0123456789abcdef';
Color.create=function create(a,b,c,d){return new Color(a,b,c,d);}
Color.blend=function(a,b){return new Color(a).blend(b);}
Color.prototype.max = function(a,b,c,d){
a=new Color(a,b,c,d);
b=Math.max;
return new Color().set(b(a.r,this.r,255),b(a.g,this.g,255),b(a.b,this.b,255),b(a.a,this.a,255));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment