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