2015-09-05 57 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