Abdallah.BeraYda
Abdallah.BeraYda

Reputation: 3

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

Upvotes: 0

Views: 312

Answers (2)

Blindman67
Blindman67

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

Rupesh babu Shrestha
Rupesh babu Shrestha

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

Related Questions