简体   繁体   中英

Drawing with HTML 5 canvas rectangles (pixel size) gets a black rectangle instead of blue?

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>

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

ctx.fillStyle = "rgb(" + [red,green,blue].join(',') + ")";

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM