2012-05-18 159 views
42

嗨,我有一個關於動態創建使用JavaScript的畫布的問題。HTML5動態創建畫布

我創建這樣一個帆布:

var canvas = document.createElement('canvas'); 
canvas.id  = "CursorLayer"; 
canvas.width = 1224; 
canvas.height = 768; 
canvas.style.zIndex = 8; 
canvas.style.position = "absolute"; 
canvas.style.border = "1px solid"; 

但是當我試圖找到它,我得到一個null值:

cursorLayer = document.getElementById("CursorLayer"); 

我是不是做錯了?有沒有更好的方式來使用JavaScript創建畫布?

+1

的[添加帆布與JavaScript的網頁(http://stackoverflow.com/questions/9152224/add-canvas-to-a-page-可能的複製用-javascript) – Vadzim

回答

64

問題是,您不要將您的畫布元素插入到文檔正文中。

只需做到以下幾點:

document.body.appendChild(canvas); 

例子:

var canvas = document.createElement('canvas'); 
 

 
canvas.id = "CursorLayer"; 
 
canvas.width = 1224; 
 
canvas.height = 768; 
 
canvas.style.zIndex = 8; 
 
canvas.style.position = "absolute"; 
 
canvas.style.border = "1px solid"; 
 

 

 
var body = document.getElementsByTagName("body")[0]; 
 
body.appendChild(canvas); 
 

 
cursorLayer = document.getElementById("CursorLayer"); 
 

 
console.log(cursorLayer); 
 

 
// below is optional 
 

 
var ctx = canvas.getContext("2d"); 
 
ctx.fillStyle = "rgba(255, 0, 0, 0.2)"; 
 
ctx.fillRect(100, 100, 200, 200); 
 
ctx.fillStyle = "rgba(0, 255, 0, 0.2)"; 
 
ctx.fillRect(150, 150, 200, 200); 
 
ctx.fillStyle = "rgba(0, 0, 255, 0.2)"; 
 
ctx.fillRect(200, 50, 200, 200);

+8

或者只是使用'document.body.appendChild(canvas)'(你不必用getElementsByTagName來搜索它) - 它是文檔對象的一個​​屬性。 – Gerrat

+0

@Gerrat好的。謝謝!但是,這兩種方式都是可能的。 – VisioN

+0

非常感謝!只有我必須等待7分鐘才能接受你的awnser xD –

0

這是因爲您在DOM加載之前調用它。首先,創建元素並添加一些元素,然後在DOM加載之後調用它。在你的情況下,它應該看起來像:

var canvas = document.createElement('canvas'); 
canvas.id  = "CursorLayer"; 
canvas.width = 1224; 
canvas.height = 768; 
canvas.style.zIndex = 8; 
canvas.style.position = "absolute"; 
canvas.style.border = "1px solid"; 
window.onload = function() { 
    document.getElementById("CursorLayer"); 
} 
+0

這是錯誤的,創建一個新元素不會觸發window.onload ... – pasx

+0

它不會,但創建後不能調用太快的元素。創建元素並調用它將返回null,但是如果您稍等或添加window.onload,它將返回HTMLElement。 – goblin01