1
0
mirror of https://github.com/Jermolene/TiddlyWiki5 synced 2024-11-17 15:24:50 +00:00
TiddlyWiki5/editions/tw2/source/tiddlywiki/js/RGB.js
2012-11-16 21:20:27 +00:00

60 lines
1.6 KiB
JavaScript
Executable File

//--
//-- RGB colour object
//--
// Construct an RGB colour object from a '#rrggbb', '#rgb' or 'rgb(n,n,n)' string or from separate r,g,b values
function RGB(r,g,b)
{
this.r = 0;
this.g = 0;
this.b = 0;
if(typeof r == "string") {
if(r.substr(0,1) == "#") {
if(r.length == 7) {
this.r = parseInt(r.substr(1,2),16)/255;
this.g = parseInt(r.substr(3,2),16)/255;
this.b = parseInt(r.substr(5,2),16)/255;
} else {
this.r = parseInt(r.substr(1,1),16)/15;
this.g = parseInt(r.substr(2,1),16)/15;
this.b = parseInt(r.substr(3,1),16)/15;
}
} else {
var rgbPattern = /rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/;
var c = r.match(rgbPattern);
if(c) {
this.r = parseInt(c[1],10)/255;
this.g = parseInt(c[2],10)/255;
this.b = parseInt(c[3],10)/255;
}
}
} else {
this.r = r;
this.g = g;
this.b = b;
}
return this;
}
// Mixes this colour with another in a specified proportion
// c = other colour to mix
// f = 0..1 where 0 is this colour and 1 is the new colour
// Returns an RGB object
RGB.prototype.mix = function(c,f)
{
return new RGB(this.r + (c.r-this.r) * f,this.g + (c.g-this.g) * f,this.b + (c.b-this.b) * f);
};
// Return an rgb colour as a #rrggbb format hex string
RGB.prototype.toString = function()
{
var clamp = function(x,min,max) {
return x < min ? min : (x > max ? max : x);
};
return "#" +
("0" + Math.floor(clamp(this.r,0,1) * 255).toString(16)).right(2) +
("0" + Math.floor(clamp(this.g,0,1) * 255).toString(16)).right(2) +
("0" + Math.floor(clamp(this.b,0,1) * 255).toString(16)).right(2);
};