我想仅使用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);
最佳答案
<!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>
完整的工作代码