(Chrome) alpha color value (in rgba) in CSS and javascript

If I set the alpha value via rgba (r, g, b, a) in javascript for anything other than 1, the actual value set by the browser is slightly different. But the value set in CSS is an exact match.

See sample code in code-pen-site

<head> <script type="text/javascript" language="javascript"> window.onload=function() { document.getElementById("p1").style["background-color"]="rgba(255,0,0,0.3)"; } </script> </head> <body> <p>RGB colors with opacity:</p> <p id="p1">Red</p> <p id="p2">Green</p> </body> 
  • use the Chromium browser
  • press F12 to activate the Inspector
  • Inspect the "Red".
  • "Red" has the background color set to rgba (255,0,0,0,3), but in the Inspector its value is rgba (255, 0, 0, 0.298039)
  • Green has the background color set to rgba (0.255,0,0,3), and the value in the Inspector corresponds to this.

Why, if the CSS color is set using Javascript, does the number change?

+6
source share
1 answer

Firstly, my initial observation is incorrect. If you click on the "Calculation" tab to check the background-clor, this difference is observed for both CSS rules inside the "style" tag and inline in the elements. I

In the chromium source code, this implementation explains the difference in the value of 0.001961 in the alpha value

 // Convert the floating pointer number of alpha to an integer in the range [0, 256), // with an equal distribution across all 256 values. int alphaComponent = static_cast<int>( clampTo<double>(alpha, 0.0, 1.0) * nextafter(256.0, 0.0)); 

Here, if alpha is 0.3, then ฮฑComponent becomes 0.298039. (If I set alpha to any floating point in [0.0, 1.0], the number shown by webInspector corresponds to the alphaComponent value obtained from the formula above.

+2
source

All Articles