以编程方式在<canvas>中的fillStyle中使用RGBa值?

Joh*_*ohn 44 javascript html5 canvas

使用<canvas>,我想使用变量设置矩形的RGBa值.

例如:

ctx.fillStyle = "rgba(32, 45, 21, 0.3)";
Run Code Online (Sandbox Code Playgroud)

工作正常,但使用变量:

var r_a =  0.3;
ctx.fillStyle = "rgba(32, 45, 21, r_a)";
Run Code Online (Sandbox Code Playgroud)

不起作用.

显然fillStyle只接受一个字符串.那么如何使用某个变量设置rgba值的值而不是显式定义值呢?

CMS*_*CMS 94

您只需要连接r_a变量以正确构建字符串:

var r_a = 0.3; 
ctx.fillStyle = "rgba(32, 45, 21, " + r_a + ")"; 
Run Code Online (Sandbox Code Playgroud)

  • 您还可以使用新的HTML模板字符串:`cts.fillStyle = \`rgba(32,45,21,$ {r_a})\`;`.这允许插值,这是你想要做的事情. (7认同)

Fab*_*ger 19

ctx.fillStyle = "rgba(32, 45, 21, "+r_a+")"; 
Run Code Online (Sandbox Code Playgroud)

它是字符串连接.


Sim*_*wsi 8

我参加派对的时间很晚,但我遇到了类似的问题并以稍微不同的方式解决了这个问题.

由于我需要在不同的alpha级别重用填充颜色,因此我使用了JavaScript替换方法:

colurfill = "rgba(255, 255, 0, [[opacity]])";
ctx.fillStyle = colurfill.replace("[[opacity]]", "0.5");
:
:
ctx.fillStyle = colurfill.replace("[[opacity]]", "0.75");
Run Code Online (Sandbox Code Playgroud)

显然,它不必是变化的alpha级别,它可能是其他渠道之一.

  • 稍微改变一下(用charset = UTF-8),color ="rgba(255,255,0,α)"; colour.replace("α",0.5); //可以在这里使用数字 (3认同)

Nic*_*eat 7

var r_a = 0.3
ctx.fillStyle = `rgba(32, 45, 21, ${r_a})`;
Run Code Online (Sandbox Code Playgroud)

这些称为模板文字 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

在美国键盘上,反引号 `` 通常出现在数字 1 的左侧。