holmberd
holmberd

Reputation: 2609

Using fillrect on multiple canvas


I'm using two canvas elements that are seperated from each other in position, and I'm trying to use fillRect two draw them each with a different color using fillRect. The problem is that only one canvas gets filled using fillRect(i.e. "blue" in the code example below). I can get them both in different colors using css style=background-color, but I'm more interested in why I fillRect isn't working for me in this case.

Thanks for your help.

Here is my HTML code

<body style="position:relative">
<div id='c1' style="position:absolute; top:0px; left:0px; z-index:1">  
    <canvas id='canvas1' width='150' height='150'>
          Your browser does not support HTML5 Canvas.
    </canvas>
</div>
<div id='c2'style="position:absolute; top:0px; left:200px; z-index:2">
    <canvas id='canvas2' width='150' height='150'>
          Your browser does not support HTML5 Canvas.
    </canvas>
</div>
</form>

Here is my JavaScript code inside the script tags:

window.onload = function () {

    // get all canvas elements
    var canvasList = document.getElementsByTagName("canvas"); 

    var ctx = canvasList[0].getContext("2d");
    var ctx2 = canvasList[1].getContext("2d");

    //canvas1
    ctx.fillStyle = "blue";
    ctx.fillRect(0,0,150,150);

    //canvas2
    ctx2.fillStyle = "red";
    ctx2.fillRect(200,0,150,150);
}

Upvotes: 1

Views: 1071

Answers (1)

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

It is working, you are drawing the second rectangle off the canvas. Start it at (0,0) and not (200,0):

//canvas2
ctx2.fillStyle = "red";
ctx2.fillRect(0,0,150,150);

Below is an example snippet:

// get all canvas elements
var canvasList = document.getElementsByTagName("canvas"); 

var ctx = canvasList[0].getContext("2d");
var ctx2 = canvasList[1].getContext("2d");

//canvas1
ctx.fillStyle = "blue";
ctx.fillRect(0,0,150,150);

//canvas2
ctx2.fillStyle = "red";
ctx2.fillRect(0,0,150,150);
<div id='c1' style="position:absolute; top:0px; left:0px; z-index:1">  
  <canvas id='canvas1' width='150' height='150'>
    Your browser does not support HTML5 Canvas.
  </canvas>
</div>
<div id='c2'style="position:absolute; top:0px; left:200px; z-index:2">
  <canvas id='canvas2' width='150' height='150'>
    Your browser does not support HTML5 Canvas.
  </canvas>
</div>

Upvotes: 2

Related Questions