UPDATE: You updated the question but the solution should be similar.(更新:您更新了问题,但解决方案应该相似。)
My solution would be as follows:(我的解决方案如下:)
Find the interval in which the value x is in-between (a,b = interval start and end)
(查找x值介于其间的(a,b = interval start and end)
)
Get the colors for this interval (c1, c2)
(获取此间隔的颜色(c1, c2)
)
Find the gap for red green and blue values for c1 and c2 (ex. r_gap = r2-r1)
(找出c1和c2的红色,绿色和蓝色值的间隙(ex. r_gap = r2-r1)
)
Calculate r = r1 + r_gap * |x - a / interval_length|
(计算r = r1 + r_gap * |x - a / interval_length|
)
And you should have your r,g,b
values.(并且您应该具有r,g,b
值。)
Example:(例:)
const colors = [[4, 189, 237], [99, 19, 0], [255, 248, 3], [253, 45, 45]] const range = [-1, 0, 0.5, 1] const inBetween = (x, a, b) => x >= a && x <= b const toRGB = x => { for (let i = 0; i < range.length; i++) { const m = range[i] const n = range[i + 1] if (inBetween(x, m, n)) { const c1 = colors[i] const c2 = colors[i + 1] const rangeDiff = n - m const ratio = Math.abs((x - m) / rangeDiff) const [r, g, b] = c1.map((e, i) => { const e1 = c1[i] const e2 = c2[i] return Math.round(e1 + (e2 - e1) * ratio) }) console.log(r, g, b) return [r, g, b].reduce((p, c) => `${p}${c.toString(16).padStart(2, '0')}`, '#') } } if (x < range[0]) return 'white' // below range return 'red' // above range } const element = document.createElement('div'); let linearGradient = '' for (let i = range[0]; i < range[range.length - 1]; i += 0.01) linearGradient += toRGB(i) + ',' element.style.backgroundImage = `linear-gradient(to right,${linearGradient}${toRGB(range[range.length -1])})`; document.body.append(element);
div { width: 500px; height: 40px; float: left; }
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…