2015-09-05 56 views
0


使用fillrect我使用的是彼此的位置分隔2个画布元素,我试图使用fillRect两队战平他们每人使用fillRect不同的颜色。问题是只有一个画布被填充,使用fillRect即在下面的代码示例中为“蓝色”)。我可以使用不同的颜色使用css style = background-color,但我更感兴趣的是为什么我fillRect在这种情况下不适用于我。多帆布

感谢您的帮助。

这里是我的HTML代码

<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> 

这里是我的JavaScript代码的脚本标签中:

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); 
} 
+0

尝试分配每个画布不同的ID,然后使用'的document.getElementById(“cavas1 “);'。 – Zak

回答

1

这是工作,您绘制第二个矩形了画布。在(0,0)启动它,而不是(200,0)

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

下面是一个例子片段:

// 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>

+0

我错过了谢谢,我想我的咖啡更多。 – holmberd

+0

@holmberd。请点击绿色复选标记以接受Spencer Wieczorek的正确答案。这样你解决的问题就会从需求答案列表中删除。谢谢! – markE

+1

@markE我做了,但显然在他编辑他的答案之前,现在都已修好。谢谢你让我知道。 – holmberd