简体   繁体   中英

Uncaught TypeError: Cannot read property 'appendChild' of null?

Error

two.js:3390 Uncaught TypeError: Cannot read property 'appendChild' of null
at root.Two.appendTo (two.js:3390)
at test2.html:14

The error happens in this line in two.js

elem.appendChild(this.renderer.domElement);

this is my code

<!DOCTYPE html>
<html>
<head>

<script src="./two.js"></script>


</head>

<body>
<script>
var elem = document.getElementById('draw-shapes');
var params = { width: 285, height: 200 };
var two = new Two(params).appendTo(elem);

var circle = two.makeCircle(72, 100, 50);

circle.fill = '#FF8000';
circle.stroke = 'orangered'; 
circle.linewidth = 5;

two.update();
</script>
</body>
</html>

I just started learning Javascript. how to solve this???

Your elem variable is null because there is no element with the id draw-shapes . The only element in the html body is your script tag.

You could either make a div in the html body:

<body>
    <div id="draw-shapes"></div>
    <script> ... </script>
</body>

Or add the Two instance to the body like this:

var elem = document.body;
...
var two = new Two(params).appendTo(elem);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM