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)
Fab*_*ger 19
ctx.fillStyle = "rgba(32, 45, 21, "+r_a+")";
Run Code Online (Sandbox Code Playgroud)
它是字符串连接.
我参加派对的时间很晚,但我遇到了类似的问题并以稍微不同的方式解决了这个问题.
由于我需要在不同的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级别,它可能是其他渠道之一.
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 的左侧。
| 归档时间: |
|
| 查看次数: |
73106 次 |
| 最近记录: |