[英]Javascript “Variable Variables”: how to assign variable based on another variable?
[英]How to assign value of variable to another method in javascript?
我的代码如下
function myFunction(a,b,d)
{
var R = a;
var G = b ;
var B = d ;
var L = "(";
var C = ",";
var Rp = ")";
var E = L ;
var ic = '"';
var prefix = "RGB";
var color = ic+prefix + L + R+ C + G + C + B + Rp+ic;
alert(color)
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle = color;
}
如果我调用上述函数例如myFunction(10,20,30);
alert(color);
打印“ rgb(10,20,30)”,但我不知道如何将颜色的值分配给ctx.fillStyle既然我要进行动态应用程序,我需要传递不同的color值,现在代码不work和ctx.fillStyle = color;
执行代码时打印。 如果有人可以告诉我如何将颜色的值分配给ctx.fillStyle方法,我将非常感激。
只要提供的值是有效的颜色值,就可以根据需要为所需的颜色值引用变量。
根据提供的代码,您似乎正在使用RGB
而不是rgb
。
首先,“ color”是一个字符串变量,要将其用作代码段,请使用eval();
功能。 其次,在画布上设置一些可见区域以查看代码是否真正起作用,即ctx.fillRect()。 最后,确保您的文档类型声明为<!DOCTYPE html>
,我希望是。
这是代码的工作版本(在FF 11.0中对我有用):
<!DOCTYPE html>
<html>
<head>
<script >
function myFunction(a,b,d)
{
var R = a;
var G = b;
var B = d;
var L = "(";
var C = ",";
var Rp = ")";
var E = L ;
var ic = '"';
var prefix = "RGB";
var color = ic+prefix + L + R+ C + G + C + B + Rp+ic;
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle=eval(color); //convert string to code.
ctx.fillRect(0,0,150,75);//any size greater than 0
}
</script>
<body>
<button onclick="myFunction(200,0,0);">click me</button>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.