Having trouble with the Canvas Element in Three.js not displaying correctly? All I can see is a black

Hello everyone, I'm fairly new to utilizing three.js and I've been attempting to replicate a code snippet that I stumbled upon in an Observable notebook within a fiddle. If you're curious, here is the original code block: Despite my best efforts, all I seem to get when running the code is a large black box. I thought that I had correctly added the group materials and light elements to the scene, but all I see is darkness. Any assistance on this issue would be greatly appreciated. Below is the code that I have been working with:

 canvas {
  display: block;
 }

initiateThree();

function initiateThree() {

 data = [
        [3,2,1],
        [6,5,4],
        [8,7,6],
        ]

 var i =1;

 height = 500
 fov = 18
 aspect = 500 / 500
 near = 0.1
 far = 1000

 loader = new THREE.TextureLoader()

 function update() {
  cubeGroup.rotation.y += 0.001;
 }

 function render(scene) {
   renderer.render(scene, camera);
 }

const scene = new THREE.Scene(); // New Addition

const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(-4, 1, 4);

cubeGeometries = data.map(row=>{
  return row.map(c=>{
  return new THREE.BoxGeometry( 0.2, c/8, 0.2 );
 })
})

const cubeMaterial =  new THREE.MeshStandardMaterial({
map:loader.load('https://threejsfundamentals.org/threejs/lessons/resources/images/compressed-but-large-wood-texture.jpg')
});

cubeMaterial.color.convertSRGBToLinear();

const cubeMeshes = cubeGeometries.map(row=>{
 return row.map(cubeGeometry => new THREE.Mesh( cubeGeometry, cubeMaterial ))
})

// And so on...

document.body.appendChild( renderer.domElement );
}

In case you'd like to check it out for yourself, here is the link to the fiddle containing my attempt at replicating the code: https://jsfiddle.net/bullybear/m826gkrt/326/

Answer №1

Your code is missing a few key components:

  • Make sure to include an animation loop.
  • The camera should be adjusted to look at the boxes.
  • Update to the latest version of three.js (currently r118) and remove any outdated code.

let scene, camera, renderer;

let cubeGroup;

init();
animate();

function init() {

  const data = [
    [3, 2, 1],
    [6, 5, 4],
    [8, 7, 6],
  ]

  var i = 1;

  height = 500
  fov = 18
  //aspect = width / height
  aspect = 500 / 500
  near = 0.1
  far = 1000

  loader = new THREE.TextureLoader()


  scene = new THREE.Scene(); // ADDED

  camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  camera.position.set(-4, 1, 4);
    camera.lookAt( scene.position );


  //max = Math.max.apply(Math, data.map(d=>Math.max.apply(this,d))) 

  cubeGeometries = data.map(row => {
    return row.map(c => {
      //return new THREE.BoxGeometry( 0.2, c/max, 0.2 );
      return new THREE.BoxBufferGeometry(0.2, c / 8, 0.2);
    })
  })


  const cubeMaterial = new THREE.MeshStandardMaterial({
    map: loader.load('https://threejsfundamentals.org/threejs/lessons/resources/images/compressed-but-large-wood-texture.jpg')
  });
  cubeMaterial.color.convertSRGBToLinear();

  const cubeMeshes = cubeGeometries.map(row => {
    return row.map(cubeGeometry => new THREE.Mesh(cubeGeometry, cubeMaterial))
  })


  cubeGroup = new THREE.Group();
  data.forEach((row, i, iarr) => {
    row.forEach((d, j, jarr) => {
      cubeMeshes[i][j].position.set(
        i / iarr.length - 0.5,
        //d/max*0.5-0.6,
        d / 8 * 0.5 - 0.6,
        j / jarr.length - 0.5);

      //cubeMeshes[i][j].scale.set(1,4,1);
      cubeGroup.add(cubeMeshes[i][j]);
    })
  })


  const mainLight = new THREE.DirectionalLight(0xffffff, 3.0);
  mainLight.position.set(10, 10, 10);


  const ambientLight = new THREE.HemisphereLight(0xddeeff, 0x202020, 3);

  scene.add(cubeGroup);
  scene.add(mainLight);
  scene.add(ambientLight);


  renderer = new THREE.WebGLRenderer({
    antialias: true
  });

  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.outputEncoding = THREE.sRGBEncoding;
  renderer.physicallyCorrectLights = true;

  document.body.appendChild(renderer.domElement); //ADDED

}

function animate() {

  requestAnimationFrame( animate );
  cubeGroup.rotation.y += 0.001;
  renderer.render( scene, camera );

}
body {
      margin: 0;
}
canvas {
    display: block;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="41352933242401716f7070796f72">[email protected]</a>/build/three.js"></script>

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

Is it possible to create an index.html page with all the necessary head tags to prevent duplicate code across multiple html pages?

Imagine I am using app.js or a Bootstrap CDN link for all of my HTML pages, but I don't want to include it in every single page individually. Is there a way to create an index.html file that includes this so that all other HTML pages load the head fro ...

Encountering an issue where an error message indicates that a variable previously declared is now undefined

Currently, I am working on developing a small test application to enhance my coding skills. However, I have encountered a roadblock while attempting to display dummy information from a mongodb database that I have set up. I have tried various solutions bu ...

Changing the old state in React js: A step-by-step guide

I have a collection of Faq elements. Clicking on a question should display the answer for that specific question while hiding all other answers. The issue I'm facing is that even though it displays the answer for the clicked question, it fails to hi ...

Working with jQuery conditionals to manipulate JSON data

I'm working with JSON data that includes a field like this: "first_date": "2015-06-02" Using jQuery, I want to achieve something like this: if( valueOfFirstDate.substring(5, 6) == "06" ){ //change 06 to "June" } Can anyone guide me on how to e ...

Performing a MySQL query to select multiple rows and fields with the AND operator simultaneously

I've got a table: + --------------------------+---------------------------+--------------+--------+ | ID | SKU_ID | DKEY | DVAL | + --------------------------+---------------------------+----------- ...

Failure to fetch data through Axios Post method with a Parameter Object

I've encountered an issue with Axios while attempting to make a post request with a parameters object to a Laravel route. If I use query parameters like ?username=user, the post request works successfully. However, when I use an object, it fails: Be ...

Using HTML as an argument in a JavaScript function

Within a variable, I have stored an entire HTML page. $body = $myhtmlpage; <a onclick="openWin('<?php echo htmlspecialchars(json_encode($body)) ?>');" href="javascript:void(0);"> Click </a> I also have this JavaScript functio ...

What coding techniques can be used to create dynamic animation of a log stream in javascript/css

When I have a series of events in my browser, I want to display them as a list with a smooth animation effect. As each new event comes in, I'd like the existing items to slide down gracefully, making room for the new event to fade in at the top of the ...

Generating various fields within a single row

I am in the process of creating a dynamic form that should generate two new fields in the same line when the user clicks on the plus icon. Currently, the code I have only creates a single field. I attempted to duplicate the code within the function, but i ...

Having trouble getting JavaScript to select a stylesheet based on time?

I am attempting to implement two different styles based on the time of day. Here is the code I am using to select the CSS file depending on the current time: <script type="text/javascript"> function setTimedStylesheet() { var currentTim ...

Creating a file by piping the output of an asynchronous HTTP request while utilizing async await method

I have been diligently following the instructions and conducting thorough research for a whole day to figure out how to use a pipe to compile an Excel spreadsheet that is fetched through an API call. I managed to get part of the way in saving it, but unfor ...

How can one retrieve the x and y coordinates from the client's browser and pass them to the server in a Bokeh server setup?

I'm currently working on a Bokeh server app called getcoords.py. To start the server, I use the command: bokeh serve getcoords.py. The app includes a HoverTool with a CustomJS callback function and a quad glyph configured to trigger a selected event o ...

Guide to developing a method for displaying the distribution of employee salaries

I am interested in analyzing the salary distribution based on employees' job categories to evaluate compensation fairness. Here is a snippet of the dataset I am working with: Category Salary Status Analyst 35 1 Analyst ...

Unusual issue in IE causing rendering problems in reporting services

Currently, I am creating a report using Reporting Services 2008, MVC 2, and Ajax as my development technologies. When I generate the report, everything displays perfectly if there is data present. However, if there is no data, the report body gets cut off ...

Setting a cookie within an Angular interceptor

My angular interceptor function includes a request object. intercept(req: HttpRequest<any>, next: HttpHandler) { return next.handle(req); } I am looking to set my token in the request cookie under the name my-token. How can I achieve this? I ...

Website API: decouple backend and frontend functionality through an API

I am currently working on the development of a website and an app created through Cordova. The app will essentially mirror the functionalities of the website. The website is already established and heavily relies on JavaScript, with potential considerati ...

The luminosity of MeshBasicMaterial in Three.js

In my current setup with threejs, I am utilizing MeshBasicMaterial for lighting effects. Each element contains a simulated point light within. I have assigned a variable named color, defined as rgb(random value, random value, random value). I am looking ...

Unable to retrieve information from the JSON object

Here's the script I'm working with: <script type="text/javascript> function getData(username){ $.ajax({ url: '{% url "data" %}', data: { ' ...

saving the hash key in a separate array

Currently, I have a collection of key-value pairs that need to be stored in another array. However, I am facing difficulties with the logic as I am unable to keep track of which keys-values have already been assigned while iterating over the list of object ...

When working in Javascript, make sure to replace newline and carriage return characters in strings with empty spaces. Also, don't forget to replace the literal sequences and

When working with Javascript, I am looking to perform multiple string replacements as outlined below. Remove all newlines and carriage returns Swap out instances of \n with a newline character Change occurrences of \r with a carriage return char ...