This is actually something I've solved, but for curiousity sake, I was wondering if someone could explain why this is the case?
Here's my html:
<!DOCTYPE html>
<html>
<head>
<script src="three.min.js"></script>
<script src="OrbitControls.js"></script>
<script type="text/javascript" src="webgl.js"></script>
</head>
<body style="margin: 0;">
</body>
</html>
and my JS:
var scene, camera, renderer;
init();
animate();
function init(){
scene = new THREE.Scene();
var width = window.innerWidth, height = window.innerHeight;
renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);
}
This does not work, I get "Uncaught TypeError: Cannot read property 'appendChild' of null "
But when I move my webgl.js script to the body, it renders the canvas element properly.
Why does this happen? Why does my script need to be in the body to append the dom element? The renderer object returns an canvas in my console, so what's the issue?
When the script is called inside the head, the body does not exist yet. You can see this by calling console.log(document.body) in both the head and the body. You'll find that document.body is null because the body has yet to be created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With