Convert rgba colour definition string in LESS to c

2019-07-11 07:56发布

问题:

Suppose I've parsed my mixin parameters and colours are provided using rgba function.

Now I would like to mix two of those colours, but LESS mix function requires parameter instances of type color.

What I tried

...and doesn't work

  1. calling color("rgba(0,0,0,.5)")
  2. mix(@first, ~"@{second}") where @second is a string like rgba(0,0,0,0.5)

How do I convert to color?

回答1:

I'm afraid you won't find a built in function to do this in LESS.

The color() functions argument needs to be a hexadecimal or its shorthand representation.

But you can further parse the string with javascript to

  • extract the individual r,g,b and alpha values,
  • pass the individual values to the rgba() function to get a variable of type color.

You could do the first step in your original parsing. If you need to do all in LESS you can do something like this:

  @color1: "rgba(255, 255, 0, 0.5)";
  @color2: ~`@{color1}.replace(/^(rgb|rgba)\(/,'[').replace(/\)$/,']').replace(/\s/g,'')`;
  @color3: rgba(unit(`@{color2}[0]`),unit(`@{color2}[1]`),unit(`@{color2}[2]`),unit(`@{color2}[3]`));

Unfortunately the string can not be directly read into the rgba() or similar functions as they expect multiple arguments. Even with string escaping (eg. ~) the output gets formated as a single variable (~"a, b, c" becomes a, b, c and acts as a single output string for the css), so we need to get each value individually and pass it to its respective argument/variable of the rgba() function. Using the function unit() we transform a string to a number that can be used further.

For example:

  @color4: mix(red,@color3);
  .test {
      color: @color4;
  }

resulting in CSS:

  .test{
    color: rgba(255, 64, 0, 0.75);
  }