RGBA to HSLA css color converter
Converts base 16 RBGA colors to css style HSLA color values with javascript.
by nilloc
HTML
<div id='output'>
<label for="rgb">rgba</label>
<input type="text" id="rgb" value="255, 188, 0, 1">
<input type="submit" id="convert" value="convert">
<hr>
<label for="hsla">hsla</label>
<input type="text" id="hsla">
</div>
<div id='tester'>tester</div>
CSS
div{
font-family:monospace;
color:white;
padding:20px;
}
label{
display:block;
margin-bottom:2px;
}
input{
font-family:monospace;
}
#hsla{width:250px;}
#tester{
background-color:#FFBC00;
}
JavaScript
function rgbToHsl(r, g, b, a) {
r /= 255; g /= 255; b /= 255;
let max = Math.max(r, g, b);
let min = Math.min(r, g, b);
let d = max - min;
let h;
if (d === 0) h = 0;
else if (max === r) h = (g - b) / d % 6;
else if (max === g) h = (b - r) / d + 2;
else if (max === b) h = (r - g) / d + 4;
let l = (min + max) / 2;
let s = d === 0 ? 0 : d / (1 - Math.abs(2 * l - 1));
s *= 100;
l *= 100;
return [h * 60, s+'%', l+'%', parseInt(a)];
}
let outputDiv = document.getElementById('output');
let inputText = document.getElementById('rgb');
let convertButton = document.getElementById('convert');
let outputText = document.getElementById('hsla');
let tester = document.getElementById('tester');
/* outputDiv.innerText = 'hsla('+rgbToHsl(255,128,0,1)+')'; */
function convertColor(){
inputValue = inputText.value.split(',');
outputText.value =
outputDiv.style.backgroundColor = 'hsla('+rgbToHsl(inputValue[0],inputValue[1],inputValue[2],inputValue[3])+')';
tester.style.backgroundColor = 'rgba('+inputText.value+')';
}
convertButton.addEventListener("click", convertColor);
convertColor();