I can't seem to figure out why my three.js scene refuses to render

I have the following contents in my main.js file:

import './style.css';
import * as THREE from 'three';


// Create a new scene
const scene = new THREE.Scene();

// Define the camera with arguments for field of view, aspect ratio, and view frustrum
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth/window.innerHeight,
  0.1,
  1000,
);

const renderer = new THREE.WebGLRenderer({
  canvas: document.querySelector('.canvas'), // Specify which DOM element to use
});

renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth / window.innerHeight);
camera.position.setZ(100);


// Define sphere geometry with radius, width segments, height segments
const geometry = new THREE.SphereGeometry(15, 32, 16);
// Set wireframe true to better visualize its geometry
const material = new THREE.MeshBasicMaterial({color: 0xffff00, wireframe: true}); 

// Create a mesh (globe) using the defined geometry and material
const globe = new THREE.Mesh(geometry, material);

scene.add(globe);

function animate(){
  requestAnimationFrame(animate); // Optimize rendering

  // Implement rotation
  globe.rotateOnAxis += 0.01;
  renderer.render(scene, camera);
}
animate();

renderer.render(scene, camera);

In my index.html file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Gautam</title>
  </head>
  <body>
    <canvas id="globe">This is the canvas
    </canvas>
    <script type="module" src="./main.js"></script>
  </body>
</html>
 

However, when I run this code, nothing appears on my screen despite the main.js file executing properly.

Answer №1

You seem to encounter a few dilemmas.

document.querySelector('.canvas')

This code is meant to target elements with the class canvas, yet your DOM does not contain such an element. Instead, there is an element with the type canvas and the ID globe. Therefore, this line should be rewritten as one of the following:

document.querySelector('canvas')
document.querySelector('#globe')
document.getElementById('globe')

Moving on,

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

@Mugen87 suggests that it should be changed to

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

The current implementation sets the renderer's width to a mathematical quotient, leaving its height (the missing second parameter) as undefined, causing issues in three.js functionalities.

Additionally,

globe.rotateOnAxis += 0.01;

It seems you are trying to assign a value to rotateOnAxis, which is actually a function that requires specific parameters for axis and rotation angle. Instead of assigning a value directly, consider using it like this:

globe.rotateOnAxis(new THREE.Vector3(0, 1, 0), 0.01);

Lastly, the extra call to renderer.render(...) outside the animate() function serves no purpose and can be removed.

Answer №2

Setting the renderer size based on window dimensions:

Update the method call as follows:

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

//create a new scene
const scene = new THREE.Scene();

//define camera with field of view, aspect ratio, near and far clipping plane
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000,
);

const renderer = new THREE.WebGLRenderer({
  //specify which canvas to use
  canvas: document.querySelector('#canvas')
});

renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
camera.position.setZ(100);

//create a sphere geometry with specified parameters
const geometry = new THREE.SphereGeometry(15, 32, 16);
//set wireframe to true for better visualization
const material = new THREE.MeshBasicMaterial({
  color: 0xffff00,
  wireframe: true
});

//create a mesh using the geometry and material
const globe = new THREE.Mesh(geometry, material);

scene.add(globe);

function animate() {
  requestAnimationFrame(animate); //optimize rendering

  //apply rotation
  globe.rotateOnAxis += 0.01;
  renderer.render(scene, camera);
}
animate();
body {
      margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/build/three.min.js"></script>
<canvas id="canvas"></canvas>

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

What is the best way to locate a div element with a specific style?

What is the method to locate a div element by its style? Upon inspecting the source code in IE6, here is what I find: ...an><div id="lga" style="height:231px;margin-top:-22px"><img alt="Google"... How can this be achieved using JavaScript? ...

Does a document.onmodification event exist, or something similar?

Is there a specific event in JavaScript that triggers whenever an element is added, removed, or modified? Although lacking in detail, it is a straightforward question. ...

Steps for creating a one-sided container in CSS

I've created a container class with the following CSS: .container { margin: 0 auto; width: min(90%, 70.5rem); } This setup centers the content on the page within the container, which is great for organization. However, I'm looking to creat ...

What could be the reason my ImageMapster jquery plugin is not functioning in the Power Apps portal's code editor?

I'm attempting to add hover effects to an image map within my Power Apps portal site using the code editor. However, when I include the script: <script type="text/javascript">$('img').mapster();</script> for the desire ...

Issue with draggable div containing gmap not functioning on mobile browsers

Is it possible to make a specific div draggable without dragging the content inside, such as a gmap widget? I have tried implementing this functionality in my code and it works on a computer browser but not on a mobile browser. Here is the simplified versi ...

Finding the nearest time in an array using Javascript or jQuery

I've been attempting to retrieve the closest time from an array or list, but so far I haven't had any success with the code I found. I made some edits to it, but it didn't work as expected. I'm open to using jQuery if it would simplify ...

Tips for modifying string in key-value pairs on the client side (example using Paypal checkout demo)

Looking to integrate an online payment system into my small online business, I have decided on using PayPal. Their solution is user-friendly and can be found here: https://developer.paypal.com/demo/checkout/#/pattern/client However, I am facing an issue w ...

Steps to validate individual input text fields that create a date and display an error message if the date is not valid

Currently, I am working on a React Material UI component designed to capture a user's 'Date of Birth'. This component consists of three separate inputs for the day, month, and year. In order to enhance this functionality, I would like to im ...

Tips on transforming a JSON array object into a JSON array

**Background:** I have been utilizing lodash to eliminate the empty key from my JSON data. However, upon removal of the keys, it transforms my array into an object. For instance: { "projection": "Miller", "series": [ { "mapPolygons": { ...

What is the process for automatically activating the Enter key once moving to the next text input field?

Hey everyone, I am looking for a way to automatically trigger the enter button after the user switches to another HTML input type='text'. This is necessary for form validation. Below is the code snippet: <input type="text" class="form-contro ...

Exploring alternatives to ref() when not responsive to reassignments in the Composition API

Check out this easy carousel: <template> <div ref="wrapperRef" class="js-carousel container"> <div class="row"> <slot></slot> </div> <div class=&q ...

Creating efficient computed properties in React: a step-by-step guide

Currently, I am facing an issue with creating a table that contains checkboxes. This problem is quite frustrating, as demonstrated in the following example: I have a list of items in the format {id, value}. For each item, I generate a div element containi ...

Understanding the Code for Responsive Web Typography with line-height in ems

I am currently trying to delve into the CSS calculation process behind the styling in the code snippet provided. This code snippet is from a responsive WordPress theme, and I am struggling to decipher how the em values for the line-height of the <h> ...

VueJS - Building a Form Template Within a Modal Component

Struggling to include a template in a modal and unsure how to pass variables to the child template: Below is the main HTML for the application: <div id="example" class="container"> <button class="btn btn-primary" type="button" @cli ...

Circular container housing SVG icons next to another container using Bootstrap 4.5

Currently, I am delving into the world of Bootstrap 4.5 and SVG icons. However, I'm facing some challenges in grasping how it all comes together. My goal is to place an SVG inside a rounded-circle shape for now, positioned next to another div. Unfortu ...

Picture hidden beyond the words

I am trying to achieve a layout where an image is displayed behind an H1 tag, with the width of the image matching the width of the text. Here is my code: <div style="display: inline;"> <img src="http://img585.imageshack.us/img585/3989/m744. ...

Which is better for scrolling in Angular 2+: using HostListener or window.pageYOffset?

Which syntax is best for maximizing performance in Angular 2+? Is it necessary to use HostListener, or is it simpler to obtain the scroll position using the onscroll window event and pageYOffset? @HostListener('window:scroll', ['$event&ap ...

Managing Asynchronous Operations in Vuex

Attempting to utilize Vue's Async Actions for an API call is causing a delay in data retrieval. When the action is called, the method proceeds without waiting for the data to return, resulting in undefined values for this.lapNumber on the initial call ...

Upon completing the update to the most recent version of aurelia, I encountered an issue where the project failed to run and displayed the error message: "unable to locate module './aurelia-framework'" in webpack

My current project is based on the aurelia webpack/es2016 navigation skeleton from a couple of months back. Up until today, everything was running smoothly. However, after deleting my node_modules directory and performing a fresh npm install, the front en ...

Compatibility issues with jQuery observed in Firefox and Internet Explorer 11

Check out the code here: jsfiddle demo HTML CODE: <div class="first"> <!-- Part one --> <div class="acord_col"> <div class="img_class" id="exist_site"></div> <div class="intro_text"> </div> </div&g ...