Sometimes, we want to calculate the hex color in the middle of a gradient with JavaScript.
In this article, we’ll look at how to calculate the hex color in the middle of a gradient with JavaScript.
How to calculate the hex color in the middle of a gradient with JavaScript?
To calculate the hex color in the middle of a gradient with JavaScript, we can convert the color numbers to decimal, find the halves, and then convert the result back to hex and concatenate them.
For instance, we write:
const color1 = 'FF0000';
const color2 = '00FF00';
const ratio = 0.5;
const hex = (x) => {
return x.toString(16).padStart(2, '0')
};
const r = Math.ceil(parseInt(color1.substring(0, 2), 16) * ratio + parseInt(color2.substring(0, 2), 16) * (1 - ratio));
const g = Math.ceil(parseInt(color1.substring(2, 4), 16) * ratio + parseInt(color2.substring(2, 4), 16) * (1 - ratio));
const b = Math.ceil(parseInt(color1.substring(4, 6), 16) * ratio + parseInt(color2.substring(4, 6), 16) * (1 - ratio));
const middle = hex(r) + hex(g) + hex(b);
console.log(middle)
We define the hex
function that converts the decimal number x
to a hex string with toString
and the prepend 0’s to it until it reaches the length of 2 with padStart
.
Next, we call Math.ceil
with the hex color multiplied by the ratio
.
Then we add the 2nd color string converted to a decimal number multiplied by 1 - ratio
.
Finally, we convert the decimal numbers back to hex strings with hex
and concatenate them together.
Therefore, middle
is '808000'
.
Conclusion
To calculate the hex color in the middle of a gradient with JavaScript, we can convert the color numbers to decimal, find the halves, and then convert the result back to hex and concatenate them.