JSFiddle - React, Tailwind, and code Playground
by Walter Rumsby
HTML
<div id="foo"></div>
CSS
div {
width: 200px;
height: 200px;
background-color: #16C7E0;
border: 4px solid #16C7E0;
}
JavaScript
function convert(color, alpha) {
var result = (color - ((1 - alpha) * 255))/alpha;
return Math.round(result);
}
var ColorUtils = {
// TODO: needs a much better name
// TODO: support hex and rgb colors
opacity: function(hexColor, opacity) {
// TODO: memoize result
var originalRgb = ColorUtils.toRgb(hexColor),
newRgb = {},
rgbString = '';
newRgb = {
r: convert(originalRgb.r, opacity),
g: convert(originalRgb.g, opacity),
b: convert(originalRgb.b, opacity)
};
rgbString = 'rgb(' + newRgb.r + ', ' + newRgb.g + ', ' + newRgb.b + ')';
return rgbString;
},
toRgb: function(hexColor) {
// TODO: memoize result
hexColor = hexColor.indexOf('#') === 0 ? hexColor : '#' + hexColor;
var cachedValue, rgb;
// Use JavaScript memoization to avoid recalculation
if (!this.toRgb.cache) {
this.toRgb.cache = {};
}
cachedValue = this.toRgb.cache[hexColor];
if (cachedValue) {
return cachedValue;
}
// TODO: RgbColor as a Type?
rgb = {
r: Math.round(parseInt(hexColor.substring(1, 3), 16)),
g: Math.round(parseInt(hexColor.substring(3, 5), 16)),
b: Math.round(parseInt(hexColor.substring(5, 7), 16))
};
this.toRgb.cache[hexColor] = rgb;
return rgb;
}
};
var color = ColorUtils.opacity('#16C7E0', 0.6);
alert(color);
document.getElementById('foo').style['backgroundColor'] = color;