-2

What's the result of rgba()function in CSS?Why is it wrapped by two quotes? The b variable is a number, why there are two plus around it, and why does it also have double quotation?

var size = 50;
var offset = 20;

for (var i = 0; i < 10; i = i + 1) {
  var b = i * 25;
  var rgba = "rgba(0, 0, " + b + ", 0.5)";
  c.fillStyle = rgba;
  c.fillRect(offset, offset, size, size);
  offset = offset + 20;
}
Kaiido
  • 123,334
  • 13
  • 219
  • 285
louis du
  • 3
  • 2
  • Is built-in where? What language or/and framework is this? – A_kat Dec 23 '19 at 10:51
  • 1
    I think this is javascript, and this might help: https://stackoverflow.com/questions/1957346/programmatically-use-rgba-values-in-fillstyle-in-canvas – Brendan Dec 23 '19 at 10:55
  • 1
    the language is javascript,fillstyle is HTML canvas property and fillRect is HTML canvas fillRect() Method. – louis du Dec 23 '19 at 14:55

1 Answers1

0

In var rgba = "rgba(0, 0, " + b + ", 0.5)"; the double quotes are not around + b + but around rgba(0, 0, and , 0.5), forming two fixed parts of this string expression where the value of b is inserted (after automatic conversion to string).

This expression builds a string like rgba(0, 0, 50, 0.5) (when i is 2, leading to a b of 50) and stores it in the rgba variable.

EDIT
Let's insert some linebreaks for readability:

var rgba = "rgba(0, 0, " + 
            b + 
            ", 0.5)";

The expression consists of three parts that are added together: a string constant ("rgba(0, 0, "), the (number-type) variable b and another string constant (", 0.5)"). The result will be a string.

The + operator can be an arithmetic operator or (as is used here) a string concatenation operator.

Because you are adding a string and a number, you are using string concatenation (instead of arithmetic addition) and the number is converted to a string first. The result is a string where the third part of the expression is added to.

The result ("rgba(...)") is assigned to c.fillStyle, which interprets it as a color.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
  • b is a number,if a number convert to string,just use +b,right? if that ,why there are two plus abround it ,and also have a double quotes? – louis du Dec 23 '19 at 14:55
  • No, the number is converted to string because you add a number (`b`) to a string (`"rgba(0, 0, "`). And then you add another string (`", 0.5)"`) to that result. The `+` operator can be string concatenation or numerical addition (`1+b` would produce 51 if b was 50) – Hans Kesting Dec 23 '19 at 15:05