Here's a simple function that creates a CSS color string from RGB values ranging from 0 to 255:
function rgb(r, g, b){
return "rgb("+r+","+g+","+b+")";
}
Alternatively (to create fewer string objects), you could use array join():
function rgb(r, g, b){
return ["rgb(",r,",",g,",",b,")"].join("");
}
The above functions will only work properly if (r, g, and b) are integers between 0 and 255. If they are not integers, the color system will treat them as in the range from 0 to 1. To account for non-integer numbers, use the following:
function rgb(r, g, b){
r = Math.floor(r);
g = Math.floor(g);
b = Math.floor(b);
return ["rgb(",r,",",g,",",b,")"].join("");
}
You could also use ES6 language features:
const rgb = (r, g, b) =>
`rgb(${Math.floor(r)},${Math.floor(g)},${Math.floor(b)})`;