Home > Enterprise >  Is there anything wrong with using decimal values for the colors in an RGBA color string?
Is there anything wrong with using decimal values for the colors in an RGBA color string?

Time:09-04

I am using canvas in Javascript and I have some code that looks like this at the moment:

const color = [ 0.3, 0.25, 0.12 ]; // in the actual code this is returned from a function

const r = Math.floor(color[0] * 255);
const g = Math.floor(color[1] * 255);
const b = Math.floor(color[2] * 255);

context.fillStyle = `rgba(${r}, ${g}, ${b}, 1.0)`;

Notice how I am calling Math.floor on each of the color values, so that each red, green, and blue value is an integer between 0 and 255.

However, do I need to do this? Is there anything wrong with a CSS color string being something like..

rgba(233.34, 212.13, 67.82, 1.0)

It seems to work when I test it in the browser's inspector, but I'm not sure if this works on all devices, or if it has any performances considerations. Ideally I am looking for the most efficient and most widely supported solution.

CodePudding user response:

That syntax is perfectly valid and mostly supported, but not absolutely everywhere.

rgba is an alias for rgb, whose arguments can be

rgb( [<number> | none]{3} [ / [<alpha-value> | none] ]? )

and a number can be, in the current standard

either an integer, or zero or more decimal digits followed by a dot (.) followed by one or more decimal digits

MDN reports that the basic rgba is supported pretty much everywhere, but the first major browser versions that supported float values in parameters are Chrome 66, Edge 79, and Firefox 52 (2018 ish). Very, very few users are still using browsers from before then, but there are still a small number.

Is it worth going to integers instead of decimals to support those users? That's up to you.

or if it has any performances considerations

No.

CodePudding user response:

mdn says that it accepts a <number> data type, which accepts decimals in contrast to <integer> so it's fine

CodePudding user response:

According to the specification, you should round them (but I think Math.round is better) or just use percentages so you can keep decimal values, as the color part should be integers or percentages. If you check the computed values in inspector, you will see the decimals are rounded when rendering.
However, accroding to MDN, decimals are also acceptable. Actually I have just tested decimal values on Internet Explorer 11, which still works fine. So it's basically supported by all browsers and you can just choose either one. There won't be any noticeable performance impacts as well.

  • Related