JSFiddle - React, Tailwind, and code Playground
by blesh
JavaScript
/**
* Copyrignt (c) Ben Lesh http://www.benlesh.com
* MIT Licensed
*/
var Color = (function (window, document) {
function Color(value) {
var HEX = /^#?([\da-f]{2})([\da-f]{2})([\da-f]{2})$/i,
RGB = /^rgb\(\s*(\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\s*\)$/,
r, b, g;
var hex = HEX.exec(value);
if (hex) {
r = +('0x' + hex[1]);
g = +('0x' + hex[2]);
b = +('0x' + hex[3]);
} else {
var origVal = value;
if (!RGB.test(value) && window.getComputedStyle) {
var div = document.createElement('div'),
span = document.createElement('span');
div.style.color = '#000';
span.style.color = value;
div.appendChild(span);
document.body.appendChild(div);
value = window.getComputedStyle(span).color;
span.remove();
div.remove();
}
var rgb = RGB.exec(value);
if (rgb) {
r = +rgb[1];
g = +rgb[2];
b = +rgb[3];
}
if(value != origValue && r === 0 && g === 0 && b === 0 && origVal.toLowerCase() !== 'black') {
r = g = b = undefined;
}
}
this.r = r;
this.g = g;
this.b = b;
};
Color.prototype.toString = function () {
return '#' + toHex(this.r) + toHex(this.g) + toHex(this.b);
};
Color.prototype.valueOf = function () {
return this.toString();
};
function toHex(n, padding) {
return pad(n.toString(16), 2);
}
function pad(n, padded) {
var s = '' + n;
while (s.length < padded) {
s = '0' + s;
}
return s;
};
return Color;
}(window, document));
var c1 = new Color('purple');
var c2 = new Color('#ff0000');