Abdallah.BeraYda Abdallah.BeraYda - 1 month ago 19
Javascript Question

An error in the creation of canvas by Javascript elements

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

Answer
<!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