2016-10-22 12 views
0

我想只有JavaScript元素 創建一個畫布,但我發現了一個錯誤:通過JavaScript元素在創作油畫的誤差

Uncaught TypeError: Cannot read property 'appendChild' of null

我的JavaScript代碼是:

// create the canvas on the page : 
var myPageCanvas = document.createElement("canvas"); 

    // Assigne Id to thin canvas :   
myPageCanvas.id = 'c'; 

// custumize canvas :  
myPageCanvas.height = 300; 
myPageCanvas.width = 500; 
myPageCanvas.style.display = "block"; 
myPageCanvas.style.margin = "50px auto"; 

// Add the canvas on the page : 
document.body.appendChild(myPageCanvas); 
+0

你複製和粘貼代碼,或者你重寫了它?我在代碼中看不到任何問題。 – youssouf

+0

當我使用谷歌瀏覽器的控制檯,說這是不能讀屬性'appendChild'null,我的代碼是在問題=) –

+1

您的網頁似乎確實包含元素或您沒有關閉標記。 – youssouf

回答

0
<!DOCTYPE html> 
<html> 
<body> 
<p>Click the button to append canvas.</p> 

<button onclick="myFunction()">Append</button> 

<script> 
function myFunction() { 
    var myPageCanvas = document.createElement("canvas"); 

    // Assigne Id to thin canvas :   
myPageCanvas.id = 'c'; 

// custumize canvas :  
myPageCanvas.height = 300; 
myPageCanvas.width = 500; 
myPageCanvas.style.backgroundColor = "lightgrey"; 
myPageCanvas.style.display = "block"; 
myPageCanvas.style.margin = "50px auto"; 

// Add the canvas on the page : 
document.body.appendChild(myPageCanvas); 
} 
</script> 

</body> 
</html> 

完整的工作代碼

+0

謝謝===>解決 –

+0

最受歡迎:)您發佈的代碼沒有問題。我想這裏有一些語法問題或者你沒有發佈的東西。所以我寫了完整的代碼。 –

+0

問題是JS代碼在加載窗口之前執行,因此您的答案只能通過在按鈕上執行代碼來間接解決問題。 Blindman67的答案更直接,因此更通用。 – markE

2

你很可能運行腳本的document.body的有蜜蜂前創建。

要麼把腳本在身上的標籤,或者使用document.addEventListener("load",function(){ your script })這樣,當頁面加載的代碼運行和身體元素創建