my code is as follow
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;
}
if i call the above function for example myFunction(10,20,30);
alert(color);
prints "rgb(10,20,30)" but i don't know how to assign the value of color to ctx.fillStyle Since i want to make dynamic application i need pass different value of color , right now the code doesn't work and ctx.fillStyle = color;
is printed when code is executed. I will be thankful if some one can tell me how to assign the value of color to ctx.fillStyle method.
You are able to reference a variable for the desired color value as you're wanting to do, so long as the value being provided is a valid color value.
Based off of your provided code, it appears that you are using RGB
instead of rgb
.
First of all, "color" is a string variable here and to use it as a code segment use eval();
function. Secondly, set some visible area in the canvas to see if the code is really working ie ctx.fillRect(). Lastly, make sure your document type is declared as <!DOCTYPE html>
which I hope is .
Here is the working version of the code (works for me in 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.