Convert opacity to hex in javascript

What would be the preferred way to convert opacity (0 - 1) to hex (00 - ff) in Javascript?

My thoughts is to use the if statement to check if the opacity is between 1 and 0.95, and then use ff. Work to 0.

+3
source share
3 answers

At the most basic level, you simply convert the decimal to hexadecimal: How do I convert the decimal to hex in JavaScript? :

yourNum = yourNum.toString(16);

The range 0.0 - 1.0 represents only the percentage format of the range 0-255. So multiply your value (e.g. 0.5 * 255), and then convert it to hex, you will get the correct value.

+7

:

Math.floor(0.0 * 255).toString(16);   // Returns '00'
Math.floor(0.5 * 255).toString(16);   // Returns '75'
Math.floor(1.0 * 255).toString(16);   // Returns 'FF'
+3
0
source

Source: https://habr.com/ru/post/1746461/


All Articles