简体   繁体   中英

JavaScript rounding to 1 decimal place on inline style attribute

I have function which is generating random RGBA color and if I log it to the console it is rounding to on decimal place(that is what I want), but if you open console and try this as inline style attribute on body element you can see that it's not rounding to one decimal place ? Where is the problem ?

JSFIDDLE(backgroundColor)

setInterval(function foo (){
  document.body.style.backgroundColor = ("rgba(" + Math.round(Math.random() * 255) + "," + Math.round(Math.random() * 255) + "," + Math.round(Math.random() * 255) + "," + Math.random().toFixed(1)) + ")";
},1000);

JSFIDDLE(console.log)

JS

setInterval(function foo (){
  console.log(("rgba(" + Math.round(Math.random() * 255) + "," + Math.round(Math.random() * 255) + "," + Math.round(Math.random() * 255) + "," + Math.random().toFixed(1)) + ")");
},1000);

If you compare these two fiddles you can see the difference.So why are they different? It is same function and it should be same, right ?

The browser internally stores the alpha value as 1 byte, not as a float. When for example you say you need a 0.5 alpha, the browser converts that into 1 byte integer using this:

Math.floor(255 * 0.5)

When you query the result back, it wil convert that integer back to 0-1 range by dividing with 255.

This will result in an incorrect alpha. I've tested this using this:

rgba(134,78,73,0.5) //the color outputed by javascript
rgba(134, 78, 73, 0.498039) //the color that was read back from the style

0.498039 = Math.floor(255 * 0.5) / 255; (of course with some rounding)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM