Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading