我正在尝试在网络游戏中创建一个动画的健康栏,当增加减少量时,它应该更改其颜色。运行状况栏的值可以在0到100之间。达到0时的颜色为“#FF0000”,当其填满时,其颜色应为“#00FF00”。我只需要将这个int数转换为十六进制字符串的逻辑即可。
Obs:我使用的是纯Javascript。我想没有任何插件
答案 0 :(得分:1)
实现您的想法可能不需要这种转换,并且其他颜色模型的解决方案也很合适:
import osmnx as ox
name_place = 'Aubervilliers, France'
graph_aubervillier = ox.graph_from_address(name_place ,network_type="drive_service")
edges_of_interest = graph_aubervillier[348206084][256242027]
for edge in edges_of_interest.values():
# May not have a length. Return None if this is the case.
# Could save these to a new list, or do something else with them. Up to you.
print(edge.get('length', None))
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%)`;
}
请注意,带有滑块平均值的颜色在不同型号中会有所不同。
答案 1 :(得分:0)
这应该有效:
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'/>