可能会使用js计算线性渐变的中间颜色值,写个demo记录下
<style>
#colors {
margin-top: 2rem;
display: flex;
}
#colors div {
width: 100px;
height: 100px;
}
</style>
<div id="colors">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<script>
// RGB转16进制色值
function rgbToHex(red, green, blue) {
const toHex = (colorValue) => {
const hex = colorValue.toString(16);
return hex.length == 1 ? "0" + hex : hex;
};
return "#" + toHex(red) + toHex(green) + toHex(blue);
}
// 16进制色值转RGB
function hexToRgb(hex) {
hex = hex.replace(/^\s*#|\s*$/g, "");
let red = parseInt(hex.substr(0, 2), 16);
let green = parseInt(hex.substr(2, 2), 16);
let blue = parseInt(hex.substr(4, 2), 16);
return [red, green, blue];
}
//计算线性渐变的中间颜色值
function getColorBetweenTwoColors(colorA_str, colorB_str, ratio) {
const colorA = hexToRgb(colorA_str);
const colorB = hexToRgb(colorB_str);
const r = Math.round((colorB[0] - colorA[0]) * ratio + colorA[0]);
const g = Math.round((colorB[1] - colorA[1]) * ratio + colorA[1]);
const b = Math.round((colorB[2] - colorA[2]) * ratio + colorA[2]);
return rgbToHex(r, g, b);
}
const colorA = "#FF0000"; //红色
const colorB = "#00FF00"; //绿色
const radio_arr = [0, 0.25, 0.5, 0.75, 1];
const elems = document.querySelectorAll(`#colors div`);
for (let i in radio_arr) {
elems[i].style.backgroundColor = getColorBetweenTwoColors(colorA, colorB, radio_arr[i]);
}
</script>
标签:colorA,colorB,const,16,渐变,hex,js,线性,ratio From: https://www.cnblogs.com/caroline2016/p/18102031