Search code examples
javascriptcolorsrgba

rgba color opacity animation expression


I have a question which is about when I trying to add color to my draw rectangle:

    ctx.fillStyle = "rgba(0,102,153,1)";
    ctx.fillRect(100,100,100,100);

the color in my draw rect is light blue but when I am trying to make some modification on my opacity value to make its half-transperrant:

    var opacityVar = 1;
    ctx.fillStyle = "rgba(0,102,153,opacityVar/2)";
    ctx.fillRect(100,100,100,100);

this is not working at all untill i trying:

    var opacityVar = 1;
    ctx.fillStyle = "rgba(0,102,153,"+opacityVar/2+")";
    ctx.fillRect(100,100,100,100);

this just works fine, my question is why would I need to add double "marks and +between my opacityVar/2variable?

I am trying to search this around but seems does not have a detailed information about rgba()arguments expression.Would anyone please help me with this?


Solution

  • ctx.fillStyle is a string. You are trying to execute javascript as part of your string. In order to do so, you have to execute that javascript outside of the string and then concatenate it into your string.

    this is a string   -> "rgba(0,102,153,"
    this is javascript -> opacityVar/2
    this is a string   -> ")"
    

    the + concatenates your strings and your javascript result into one string. The " tells the engine where your string starts and where it ends.

    You can also use template literals in javascript now.