这个问题在这里已有答案:
我正在尝试在我的网页游戏中创建一个动画健康栏,当增加我们的减少时,它应该改变颜色。健康栏的值可以是0到100.当颜色达到0时,颜色为“#FF0000”,当颜色为满时,颜色应为“#00FF00”。我只需要逻辑将此int数转换为十六进制字符串。
Obs:我使用的是纯Javascript。我想没有任何插件
实现您的想法可能不需要这样的转换,并且其他颜色模型的解决方案非常合适:
function fRGB(obj) {
let nVal = +obj.value;
obj.style.boxShadow = `inset 0 0 7px 6px rgb(${255 - nVal * 2.55}, ${nVal * 2.55}, 0)`;
}
function fHSL(obj) {
let nVal = +obj.value;
obj.style.boxShadow = `inset 0 0 7px 6px hsl(${nVal * 1.2}, 100%, 50%)`;
}
RGB<br><input type="range" min="0" max="100" oninput="fRGB(this)">
<br>
HSL<br><input type="range" min="0" max="100" oninput="fHSL(this)">
请注意,滑块平均值的颜色在不同型号中有所不同。
这应该工作:
const valueToColor = value => {
let gHex = Math.round(value * 255 / 100) // rule of three to calibrate [0, 100] to [00, FF] (= [0, 255])
let rHex = 255 - gHex // just the mirror of gHex
gHex = gHex.toString(16) // converting to traditional hex representation
rHex = rHex.toString(16)
gHex = gHex.length === 1 ? `0${gHex}` : gHex // compensating missing digit in case of single digit values
rHex = rHex.length === 1 ? `0${rHex}` : rHex
return `#${rHex}${gHex}00` // composing both in a color code
}
console.log(valueToColor(0)) // #ff0000
console.log(valueToColor(100)) // #00ff00
console.log(valueToColor(50)) // #7f8000
console.log(valueToColor(23)) // #c43b00
console.log(valueToColor(85)) // #26d900
我认为这比在类似线程中提供的解决方案更简单,更简单。
交互式代码段示例:
const valueToColor = value => {
let gHex = Math.round(value * 255 / 100) // rule of three to calibrate [0, 100] to [00, FF] (= [0, 255])
let rHex = 255 - gHex // just the mirror of gHex
gHex = gHex.toString(16) // converting to traditional hex representation
rHex = rHex.toString(16)
gHex = gHex.length === 1 ? `0${gHex}` : gHex // compensating missing digit in case of single digit values
rHex = rHex.length === 1 ? `0${rHex}` : rHex
return `#${rHex}${gHex}00` // composing both in a color code
}
//
const slider = document.getElementById('life')
const colorDiv = document.getElementById('color')
const valueDiv = document.getElementById('value')
const setValue = () => {
const color = valueToColor(slider.value)
colorDiv.style.backgroundColor = color
valueDiv.innerText = color
}
setValue()
slider.addEventListener('input', setValue)
#life {
width: 50%;
}
#color {
width: 100px;
height: 100px;
}
<input type="range" min="0" max="100" value="95" id="life">
<div id='color'/>
<h2 id='value'/>