-1

I have been looking around, but cannot find people with the same issue. I am at the start of learning to work with Three.js and this (Lynda.com) tutorial has instructed me to write the following php file & javascript code.

The chrome console shows the following error:

main.js:25 Uncaught TypeError: Cannot read property 'appendChild' of null
at init (main.js:25)
at main.js:36

I don't quite understand what I am doing wrong, I have created a div element with the same id.

PHP:

<?php
echo "Three JS Course";
?>


<!DOCTYPE html>
<html>
<head>
    <title>Three.js Course</title>
</head>

<body>
    <div id="webgl"></div>
</body>


JS:

function init()
{
//Create scene
var scene = new THREE.Scene();

//Create camera
var camera = new THREE.PerspectiveCamera(
    //Perspective
    45,
    //Ratio
    window.innerWidth/window.innerHeight,
    //Near clipping distance
    1,
    //Far clipping distance
    1000
);

//Create renderer
var renderer = new THREE.WebGLRenderer();
//Set renderer size
renderer.setSize(window.innerWidth, window.innerHeight);

//Get element by ID
document.getElementById('webgl').appendChild(renderer.domElement);

//Make the renderer render the scene and the camera
renderer.render(
    scene,
    camera
);
}

init();
Teije
  • 323
  • 1
  • 3
  • 16
  • Where is the JS placed in the file? – Teemu May 28 '18 at 10:01
  • Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Teemu May 28 '18 at 17:40

1 Answers1

-1

I found the solution, so I am posting an answer in case anyone else encounters this issue:

Make sure you load your scripts after the HTML file. If document.getElementById() tries to acces an element which has not yet been loaded it wont be able to find it!

Teije
  • 323
  • 1
  • 3
  • 16