I'm puzzled as to why this particular three.js demonstration isn't functioning properly

After installing three.js through npm using the command: npm install --save three, and setting up my files index.html and index.js in VS-Code, I encountered an issue. Despite copying a simple example from threejs.org, I couldn't get three.js to display properly. Instead of a rotating cube, all I saw was a blank screen when running a live server.

Below is the code for both files:

import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 
0.1, 1000 );

const renderer = new THREE.WebGLRenderer();

renderer.setSize( window.innerWidth, window.innerHeight );

document.body.appendChild( renderer.domElement );

const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material);
scene.add(cube);

camera.position.z = 5;

function animate() {
requestAnimationFrame(animate)

cube.rotation.x += 0.01;
cube.rotation.y += 0.01;

renderer.render( scene, camera )
}
animate();
 <!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" href = "index.css">
<script src = "index.js"></script>
<title >Title</title>
</head>

<body style = "margin: 0px;">


</body>
</html>

Answer №1

Upon inspecting the page in a browser and navigating to the dev tools menu, an error message is revealed:https://i.sstatic.net/RwOBC.png.

Attempting to rectify this error by adjusting the script tag with type="module" results in a new error:

Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../"
.

Evidently, the browser encounters difficulty locating the three.js JavaScript library.

A straightforward solution involves instructing the browser to load the library from a web URL upon page initialization instead of installing it through npm and subsequently integrating those installed npm files into the webpage:

<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" href = "index.css">
<!-- This script tag loads the three.js library via URL -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<title >Title</title>
</head>

<body style = "margin: 0px;">
<script src = "index.js"></script>
</body>
</html>
// import is no longer needed since the added script tag loads the library and adds the global THREE variable into the page
// import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 
0.1, 1000 );

const renderer = new THREE.WebGLRenderer();

renderer.setSize( window.innerWidth, window.innerHeight );

document.body.appendChild( renderer.domElement );

const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material);
scene.add(cube);

camera.position.z = 5;

function animate() {
  requestAnimationFrame(animate)

  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;

  renderer.render( scene, camera )
}
animate();

Additionally, it should be noted that document.body.appendChild will function properly only once the document has finished loading (which may not necessarily occur before your script executes). To address this issue, the <script> tag was positioned below the <body> tag in the HTML.

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

The Owl carousel seems to be malfunctioning as there are no error messages displayed and the div containing it disappears unexpectedly

I'm having an issue with Owl carousel. I've included the necessary owl.carousel.css, owl.carousel.js, and owl.theme.css files. Created a div with the class "owl-carousel", and called the function $(".owl-carousel").owlCarousel();. However, after ...

Issue with ng-maxlength directive

In my Angular 4 Application, I am attempting to implement validation for form inputs. Specifically, I want to restrict inputs with numbers to not accept more than 4 digits. If the input contains more than 4 digits, the form should be marked as invalid. I a ...

Configure Jest to run tests for Lit using TypeScript with Microbundle

Today, I began the process of migrating our web components to lit-html. However, when attempting to run the initial test, an error message was encountered: SyntaxError: Cannot use import statement outside a module > 1 | import {LitElement, html, css, s ...

A guide on implementing reverse routes using react-router

Is there a best practice for constructing URLs for links in my react-router based app? In the Zend Framework world of php, I would use a url helper that utilizes reverse routes. By providing the route name and parameters to a route configuration, it would ...

What is the best way to implement a switch case for the value of a property within an object in a TypeScript file?

The object I'm dealing with looks like this: {a: auth?.type === '1' || auth?.type === '2' || auth?.type === '3' ? { reason: // I need to implement a switch case here : un ...

Having trouble getting useFieldArray to work with Material UI Select component

I am currently working on implementing a dynamic Select field using Material UI and react-hook-form. While the useFieldArray works perfectly with TextField, I am facing issues when trying to use it with Select. What is not functioning properly: The defau ...

Using jQuery to replace the value of a button with a variable string that has been concatenated

I am facing a dilemma with a button on my webpage. The value displayed on the button is a combination of variables and strings, like so: $('#btn1').attr('value','question'+currid+'ans1').button('refresh'); ...

What's the secret to AngularJS's isolate scope?

I'm struggling to add animation effects to specific buttons and I can't seem to get the isolate scope to work properly. Check out this fiddle for reference: Fiddle https://jsfiddle.net/gLhveeor/4/ The issue is that the mouseenter event is trigg ...

Ordering SVG Elements with ng-repeat in AngularJS

Trying to sort or reverse a list of <g> elements using Angular's ng-repeat directive is causing rendering order issues for me. I've created a plunkr to demonstrate the problem: http://plnkr.co/edit/f2pgSq?p=preview I'm looking to util ...

Tips for indicating request parameters in Drive.Comments.list

I have successfully retrieved the default 20 comments using the code below by specifying a single fileId parameter. However, I am interested in pulling back one hundred comments or paginating to the next set of 20 out of curiosity. In my getComments funct ...

What could be causing data to be saved twice when using a mongoose callback function?

Recently, I've been intrigued by the behavior of adding a callback to the mongoose findOneAndUpdate function and how it leads to saving data twice in the database. public async addPersonAsFavorite(userId: string, friendId: string) { if (!await th ...

Discover the `.next/server` feature on Vercel - a platform where it seamlessly operates unlike on Netlify

Having trouble accessing .next/server on Vercel when running the build:rss script: { "export": "next export", "build": "next build && npm run export && npm run build:rss", "build:rss": &q ...

When setting a value through the DOM, the input's value bound with ngModel in Angular does not get updated

Trying to upload a file to calculate its hash and display it in an input box. If done correctly, the value should show in the form, but when submitting the form, the value does not get sent. Only adding a blank space by clicking on the input field works: ...

How can I use JavaScript to add a search text to the selectpicker searchbox in Bootstrap, and then automatically display the search results in the dropdown menu?

In the process of developing a web application with Razor Pages ASP.NET CORE 3.0, I have integrated a Bootstrap "selectpicker" dropdown with the attribute "data-live-search= true". The dropdown is populated with the names of employees from my model. Below ...

JavaScript function only activates on the second click

Can anyone assist me with this problem? I am attempting to retrieve the value of the image src upon clicking the tag with the class name downloadModal. I have made several attempts, and sometimes it only works on the second click, while other times it does ...

Javascript program to validate if the user input matches a single value in an array

Currently, I am working with an array: var something = ["1","2","3","4"] ; My plan is to prompt the user to select a number. If the chosen number matches any value in the array, I want to trigger a specific action. Here's my dilemma: How can I veri ...

What causes the scrollbar to not extend to the bottom when connected to another scrollbar via a JavaScript equation?

I have been working on a code that involves multiple scrollbars that are all linked together. When you move one scrollbar, the other two will move proportionally. However, due to differences in width, the scroller doesn't always reach the end of the s ...

The $.ajax request encounters an error when trying to parse the data as JSON

I am encountering an issue where my ajax call to a JSON file fails when using dataType: "json". However, changing it to "text" allows the ajax call to succeed. See the code snippet below: $.ajax({ type: "POST", url: url, dataType: "json", ...

Creating default values for MongoDB databases using bdhash in Express.js and mongoose asynchronously

What is the best way to set a default value (like bdhash which is async) for a field in my mongoose schema? Currently, I am only seeing a promise inside. I'm using async/await correctly, but why does it seem like I'm getting just a promise? I als ...

The fixed method in JavaScript is a handy tool for converting

Is it possible to implement the toFixed() method only when the input strings exceed 12 characters in length? If not, I would like the input to display normally, resembling a standard calculator app. I have experimented with a maximum character method, but ...