Reputation: 3
I want to Create a canvas with only JavaScript Eléments But I found an error :
Uncaught TypeError: Cannot read property 'appendChild' of null
My Javascript code is :
// 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);
Upvotes: 0
Views: 312
Reputation: 54128
You are likely running the script before the document.body has been created.
Either put the script in the body tag, or use document.addEventListener("load",function(){ your script })
so that the code runs when the page has loaded and the body element created
Upvotes: 2
Reputation: 222
<!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>
Complete working code
Upvotes: 0