Javascript元素创建画布时出错

时间:2016-10-22 13:11:46

标签: javascript html5 canvas html5-canvas

我想创建一个只有JavaScriptEléments的画布 但我发现了一个错误:

  

未捕获的TypeError:无法读取null

的属性'appendChild'

我的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);

2 个答案:

答案 0 :(得分:2)

您可能在创建document.body之前运行脚本。

将脚本放在body标签中,或使用document.addEventListener("load",function(){ your script })以便在页面加载并创建body元素时运行代码

答案 1 :(得分: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>

完整的工作代码