The initial Three.js demonstration is failing to function properly

I am excited to dive into learning three.js. After downloading the library from github: three.js

I attempted to run the first example of three.js as provided in the link above. However, I encountered a strange issue - the code runs perfectly fine on jsFiddle but does not work on my local machine.

Upon inspecting the console, I came across this error:

TypeError: document.body is null
[Break On This Error]   
document.body.appendChild( renderer.domElement );


Check out the Live Working Demo on jsFiddle

Below is the exact code snippet that I copied from the provided link:

And yes, I have included the three.js library correctly on the page.

    var camera, scene, renderer;
    var geometry, material, mesh;

    init();
    animate();

    function init() {

        camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
        camera.position.z = 1000;

        scene = new THREE.Scene();

        geometry = new THREE.CubeGeometry( 200, 200, 200 );
        material = new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true } );

        mesh = new THREE.Mesh( geometry, material );
        scene.add( mesh );

        renderer = new THREE.CanvasRenderer();
        renderer.setSize( window.innerWidth, window.innerHeight );

        document.body.appendChild( renderer.domElement );

    }

    function animate() {

        // note: three.js includes requestAnimationFrame shim
        requestAnimationFrame( animate );

        mesh.rotation.x += 0.01;
        mesh.rotation.y += 0.02;

        renderer.render( scene, camera );

    }

Answer №1

Ensure your code runs after the HTML document is fully parsed and the DOM is constructed. This will prevent issues with document.body returning undefined.

To accomplish this, utilize a "load" event handler:

window.onload = function() {
  // place all of your code here
};

Your jsfiddle version may have worked because the site takes care of this automatically; indicated by the top selection tool on the left-hand panel.

Additionally, exercise caution when copying code from jsfiddle as there could be hidden characters that get inadvertently included during copy/paste operations, resulting in obscure JavaScript errors.

Answer №2

To successfully execute your code, simply place it within the onload function.

window.onload = function() { // insert your code here }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Distorting three.js models by replacing colors on glb (gltf) models. Transforming blue hues to green and yellow tones to orange

Altering colors and distortion on glb (gltf) models. Blue transforms into green, while yellow shifts to orange. v106 three.js v97 GLTFLoader.js ...

Encountering Uncaught Syntax Error when attempting a request with JSON parameters

Currently, I am using Fetch to send a post request to my server while including some additional information. Here's the code snippet: var rating = document.getElementById("rating"); var ratingValue = rating.innerHTML; fetch("/films",{ method: "po ...

An error occurs due to attempting to parse the data using JSON.parse

Trying to troubleshoot a seemingly simple issue: The callback function of an AJAX post request is receiving a JSON string in the 'data' parameter. {"result":"Torte"} Manually parsing it yields the expected result: var response = JSON.parse(&ap ...

Error Alert: Attempting to access the 'prototype' property of an undefined value has resulted in a TypeError after switching to react-scripts version 4.0.3

I encountered a problem where I received the following error message: (Uncaught Error: Module build failed (from ./node_modules/source-map-loader/dist/cjs.js)). After attempting to resolve it by using npm install, a new error popped up in the console: path ...

The Child component is unable to render initially due to the Context API being undefined during the first render of the Child component

I'm struggling to ensure that a child component only renders when the Context API state I've set up is fully mounted. The Parent component fetches data from the server and sets the state based on the received information. Initially, I keep gettin ...

Using jQuery/Javascript to create a dynamic content slider

I am currently working on developing a straightforward content slider. When the page loads, my goal is to display only one item (including an image and some content) and provide a navigation system for users to move through the items. Below is the basic H ...

Incorporate a background image property using Jquery

Can anyone help me with adding the css background-image:url("xxxxx") property to my code? jQuery('#'+$trackID+' .sc_thumb').attr('src',$thumb_url); jQuery('#'+$trackID+' .sc_container').css('display& ...

How to stop form submission when Enter key is pressed in Angular

Despite scouring stackoverflow for answers, none of the solutions have worked for me. I have tried various approaches, which I will outline below: <form (keydown.enter)="$event.preventDefault()" ...> <button (keyup.enter)="skillsHandleEnter($eve ...

Tracking by $index yields an overwhelming amount of results

Encountered an error with Angular that mentioned duplicates in a repeater: To address this, I added the following line of code: rooster in rooster.uren track by $index However, this caused an unexpected issue where multiple panels were created even thoug ...

What is the Best Way to Toggle the Visibility of Specific Buttons in a Table Using Jquery?

<html> <head> <script> $( "#clickMeButton" ).click(function() { $(this).next("#hiddenButton").slideToggle( "slow", function() { // Animation complete. }); }); </script> </head> <body> <table> <tr& ...

Leverage Arrays with Bootstrap SelectPicker in Javascript

I am looking to populate a Bootstrap SelectPicker with values from an array. I am unsure of how to loop through the array to extract the values. Currently, I have manually added values to the SelectPicker like this. <!DOCTYPE html> <html> < ...

Issue creating a JWT using jsonwebtoken module in Node.js

Could someone help me troubleshoot an issue I'm having while trying to generate a JWT token? The error message "TypeError: Right-hand side of 'instanceof' is not an object" keeps appearing even though the syntax seems correct. const jsonwebt ...

The toast added to the DOM is not displaying when using the show() function

I'm experimenting with utilizing Bootstrap 5's toast component to exhibit response messages following a jquery Ajax call. For the successful part, I conclude with this code snippet: itsToastTime(response.status, response.message) let toast = $( ...

Error: Issue with hook function call detected. Struggling to locate exact source in React JS

As I dive into React for the first time, I'm working on creating a sign-up form with multiple steps. Despite reading through the material-ui documentation and learning about ReactJS, I'm struggling to pinpoint where I've gone wrong. Here&ap ...

Is there a way to rotate label text on a radar chart using chart js?

I am working with a Chart js radar diagram that contains 24 labels. My goal is to rotate each label text by 15 degrees clockwise from the previous one: starting with 'Label 1' at the top in a vertical position, then rotating 'Label 2' ...

Each time a new client connects, socket.io replicates the information

Exploring Node.js and socket.io for the first time, I have developed a small application where a table is meant to be displayed in real-time via socket.io when a function is triggered through a websocket (function triggers an "emit"). However, I'm fac ...

Ldap.js: exploring nested searches

My current task involves using ldapjs to conduct a search where the filter is dependent on the outcome of a preceding search. ldapClient.search(base1, opts1, (err1, res1) => { res1.on("searchEntry", entry => { const myObj = { attr1: entr ...

There seems to be an error with cheeriojs regarding the initialization of exports.load

I am currently using cheeriojs for web scraping, but I am encountering an issue after loading the body into cheerio. Although the body appears to be well-formatted HTML code, I am receiving errors such as exports.load.initialize. This is preventing me fr ...

Synchronizing live data from the database to the front end of a Java-powered web application

I'm currently developing a customer support web application using Java, where I need to display the status of "Customer Representatives (CR)" in the front-end - whether they are available, busy, or away on the phone. When a CR ends a call with a cust ...

What methods does Express use to precisely measure time intervals shorter than 1ms?

Recently, I started delving into the world of Express, a web framework for Node.js. While experimenting with it, I noticed that whenever a webpage rendered by Express was refreshed, a series of log messages appeared on my Linux console, as shown below: GE ...