hex convert to linear gradient
by Oleh Kotsubko
HTML
<div id="gradient"></div>
CSS
div {
width: 300px;
height: 300px;
border: 1px solid #000;
}
JavaScript
function gradientConvert(hex, alpha){
hex = hex.replace('#', '');
var r = parseInt(hex.length == 3 ? hex.slice(0, 1).repeat(2) : hex.slice(0, 2), 16);
var g = parseInt(hex.length == 3 ? hex.slice(1, 2).repeat(2) : hex.slice(2, 4), 16);
var b = parseInt(hex.length == 3 ? hex.slice(2, 3).repeat(2) : hex.slice(4, 6), 16);
return `
background: linear-gradient(rgb( ${r}, ${g}, ${b}), rgba(${r}, ${g}, ${b}, ${alpha/100}));
background: -webkit-gradient(linear, left top, left bottom, from(rgb(${r}, ${g}, ${b})), to(rgba(${r}, ${g}, ${b}, ${alpha/100})));
background: -webkit-linear-gradient(rgb( ${r}, ${g}, ${b}), rgba(${r}, ${g}, ${b}, ${alpha/100}));
background: -o-linear-gradient(rgb( ${r}, ${g}, ${b}), rgba(${r}, ${g}, ${b}, ${alpha/100}));
`;
}
const customColor = gradientConvert('#ff0000',40);
const elem = document.getElementById('gradient');
console.log(typeof(customColor), elem.style );
elem.setAttribute("style", customColor);