1
0
mirror of https://github.com/Jermolene/TiddlyWiki5 synced 2024-11-09 19:39:57 +00:00
TiddlyWiki5/archive/test/tiddlywiki.2.6.5/source/tiddlywiki/js/RGB.js

60 lines
1.6 KiB
JavaScript
Raw Normal View History

2011-11-22 14:29:29 +00:00
//--
//-- 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);
};