How do I write a RGB color value in JavaScript?

前端 未结 6 1564
不知归路
不知归路 2020-12-28 13:09

I am trying to change the color of the function swapFE() below and I can\'t figure out how to write it. I was told to change the color of the phrase node to the color value

6条回答
  •  抹茶落季
    2020-12-28 13:33

    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)})`;
    

提交回复
热议问题