Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert opacity to hex in Javascript

Tags:

javascript

hex

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

My thoughts are to use an if statement to check if opacity is between 1 and 0.95 then use ff. Work my way down to 0.

like image 396
John Hoover Avatar asked May 20 '10 19:05

John Hoover


People also ask

What is hex value for transparent color?

An alpha value of 0 (or 00 in hex strings) corresponds to fully transparent and an alpha value of 1 (or FF in hex strings) corresponds to fully opaque. If a color hex string in R does not provide an explicit alpha transparency, the color is assumed to be fully opaque.

How do you convert Rgba to hex?

Converting RGBA to hex with the #rgba or #rrggbbaa notation follows virtually the same process as the opaque counterpart. Since the alpha ( a ) is normally a value between 0 and 1, we need to multiply it by 255, round the result, then convert it to hexadecimal.


1 Answers

At the most basic level, you're just converting a decimal to hex: How to convert decimal to hex in JavaScript?:

yourNum = yourNum.toString(16);

The 0.0 - 1.0 range is just a percentage format of the 0-255 range. So multiply your value (e.g. 0.5 * 255) then convert to hex, you'll get the correct value.

like image 84
Rex M Avatar answered Oct 24 '22 19:10

Rex M