Question

I expect to draw a large blue rectangle of 320 X 240 pixels on the Canvas in Firefox but instead I get a black rectangle. I'm drawing pixels actually just to experiment and for some reason this doesn't work properly. Everything in the code seems to make sense inside the JavaScript draw function but it's a nogo? Any ideas, here's the code,

<html>
  <head>
    <title>Canvas</title>
    <script type="text/javascript">
      function draw() 
      {
        var canvas = document.getElementById("canvas");
        if (canvas.getContext) 
        {
            var ctx = canvas.getContext("2d");          
            var red = 0;
            var green = 0;
            var blue = 255;
            ctx.fillStyle = "rgb( red, green, blue)";

            for(var i = 0; i < 320; i++)
            {
                for(var j = 0; j < 240; j++)
                {                   
                    ctx.fillRect (i , j , 1, 1);
                }
            }
        }
      }
    </script>   
    <style type="text/css">
      body
      {
        margin: 50px 50px;
      }
      canvas 
      {         
        border: 1px solid black; 
      }   
      #container
      {
        position: relative;     
        width: 640px;
        height: 480px;
        margin: 0 auto;
      }
    </style>    
  </head>
  <body onload="draw();">
    <div id = "container">
        <canvas id="canvas" width="640px" height="480px"></canvas>
    </div>
  </body>
</html>
Was it helpful?

Solution

You need to use ..." + variable + "... to let the String use the variable's values. As it is you were passing rgb( red, green, blue) as the fillStyle, which then defaults to black because it's invalid

ctx.fillStyle = "rgb("+red+","+green+","+blue+")";

Demo

OTHER TIPS

ctx.fillStyle = "rgb(" + [red,green,blue].join(',') + ")";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top