Answer the question
In order to leave comments, you need to log in
How to link a number gap to a gradient?
There is an element with a numerical value, showing the color "success" of the work.
How can this number be converted to the corresponding gradient color using a scale like this?
Answer the question
In order to leave comments, you need to log in
A bit cumbersome but working code:
// Ключевые точки градиента
const red = [255, 30, 30];
const yellow = [255, 215, 74];
const green = [60, 255, 95];
const blue = [85, 145, 255];
function to_rgb(color) {
return `rgb(${color[0]}, ${color[1]}, ${color[2]})`;
}
function blend_colors(color1, color2, percentage) {
let color = [];
for (let i = 0; i < 3; i++) {
color[i] = (1 - percentage) * color1[i] + percentage * color2[i];
}
return to_rgb(color);
}
let bgColor;
if (!value) {
bgColor = "grey";
} else if (value >= 10) {
bgColor = to_rgb(blue);
} else if (value >= 8) {
bgColor = blend_colors(green, blue, (value - 8) / 2);
} else if (value >= 6) {
bgColor = blend_colors(yellow, green, (value - 6) / 2);
} else if (value >= 4) {
bgColor = blend_colors(red, yellow, (value - 4) / 2);
} else {
bgColor = to_rgb(red);
}
Two main approaches:
- use a predefined array of colors for the gradient and find a match by serial number in the array,
- set the gradient mathematically (in any color space with Hue - HSL , HSV), varying the hue value and keeping the other two components constant, then the position in H (that is, in shade) it will not be a problem to recalculate using a simple formula.
https://www.w3schools.com/colors/colors_hsl.asp
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question