Basic Block - Three.JS

My goal was to create a simple rotating 3D cube using the Three.js library for WebGL.

Despite following numerous tutorials, I can't figure out why my code only displays a black screen with no geometry.

//Setting window dimensions
var width = window.innerWidth;
var height = window.innerHeight;

//Creating renderer with smooth edges
var renderer = new THREE.WebGLRenderer({antialias:true});
//Adjusting size of renderer
renderer.setSize(width,height);
//Appending renderer to HTML document
document.body.appendChild(renderer.domElement);

var scene = new THREE.Scene;

//Adding Cube - width, height, depth
var cubeGeom = new THREE.CubeGeometry(100,100,100);
var cubeMaterial = new THREE.MeshLambertMaterial({color:0x1ec876});
var cube = new THREE.Mesh(cubeGeom,cubeMaterial);

//Rotating cube by 45 degrees
cube.rotation.y=Math.PI*45/180;

//Adding cube to scene
scene.add(cube);

//Adding Camera - FOV, Ratio, Near, Far
var camera = new THREE.PerspectiveCamera(45,width/height,0.1,10000);

//Positioning camera
camera.position.y = 160;

//Bringing camera closer 
camera.position.z = 400;

//Pointing camera towards cube
camera.lookAt(cube.position);

//Adding camera to scene
scene.add(camera);

//Defining skyBox
var skyBoxGeom = new THREE.CubeGeometry(10000, 10000, 10000);
var skyBoxMaterial = new THREE.MeshBasicMaterial({ color: 0x000000, side: THREE.BackSide });
var skyBox = new THREE.Mesh(skyBoxGeom,skyBoxMaterial);

scene.add(skyBox);

//Point Light
var pointLight = new THREE.PointLight(0xffffff);
pointLight.position.set(0,300,200);
scene.add(pointLight);

//Rendering scene
function render() {
  render.render(scene,camera);

  var clock = new THREE.Clock;

  //Rotating cube clockwise - subtracting time passed from rotation
  cube.rotation.y -=clock.getDelta();

  requestAnimationFrame(render);
}

//Calling render function
render();
canvas {
    position: fixed;
    top:0;
    left:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/threejs/r76/three.min.js"></script>

p.s. I am using the CDN link to Three.js provided by Google Developers: https://developers.google.com/speed/libraries/

Your assistance is greatly appreciated.

Thank you, Tom

Answer №1

There appears to be a small error in your JavaScript code on line 55:

render.render(scene,camera);

It should actually read as follows:

renderer.render(scene,camera);

Next time, I highly suggest checking your browser's console for errors, as the mistake was already logged there making it easy to fix.


Despite that issue, your code is working properly. The cube is rotating, albeit at a slow pace. Consider adjusting line 60 to increase the rotation speed (e.g. by multiplying the value by 100).

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

Meteor twilio SMS feature not functioning properly

I'm currently using the Twilio node for sending SMS, but I've encountered an error: sendSms is not defined Within my server folder, here is the Twilio file I have: import twilio from "twilio"; sms = { accountSid: "xxxxxxxxxxxxxxxxxxxxxxx ...

Is there a way to compel Google Maps to load within my Angular application by implementing an Angular Directive?

I am encountering an issue where my Google Map fails to display most of the time. It seems that the map is not fully rendered when the rest of my data is populated in my Angular view. Is there a way to force the map to load? I have done some research and ...

Selenium: The ultimate guide to inserting text within a div element located inside an iframe

Snippet of HTML code: <div class="listRte__editorFrame"> <iframe src="about:blank" style="height: 150px;"> #document <html> <head> <body> ...

The React component patiently waits for the necessary props before rendering

When declaring a component within another parent component, I prefer to define specific props in one file and then assign additional shared properties in the parent component. However, I am encountering an issue where the child component fails to render be ...

Why is it that only one of these functions can be operational at any given moment?

Even without the if statements, only one of the following will work at a time. To make the first one work, I have to comment out the second. <? if(isset($_POST['region'])){ echo "<script> showRecords('".$_POST['region']." ...

Incorporating a computed variable in a v-select within a VueJs endless loop

I've been attempting to utilize a computed value in a v-select component from Vuetify, but every time I select an item, it triggers an endless loop. To demonstrate the issue, I have recreated my code in this CodePen. Please be cautious as it may caus ...

Mastering the art of square bracket destructuring in React through deep comprehension of the concept

import React, { useEffect, useState } from 'react' import { Text } from 'react-native' export default function Counter() { const [count, setCount] = useState(0) useEffect(() => { const id = setInterval(() => setCount((co ...

Sending a large number of values unrestrictedly via ajax

I'm currently working on implementing a filter for the Google Maps API on our website. This filter will allow users to display information related to specific locations that they select by checking corresponding checkboxes. As I am still relatively ne ...

Transitioning between modals using Tabler/Bootstrap components in a ReactJS environment

Currently, I am constructing a Tabler dashboard and incorporating some ReactJS components into it. Initially, I used traditional HTML pages along with Jinja2 templates. However, I have now started integrating ReactJS for certain components. I prefer not t ...

Transform Ajax response into dropdown menu option

I have made an ajax call and received HTML as a response. Now, I need to convert this output into options and add them to select tags on my webpage. <div class="views-element-container"> <div class="view view-contact-view-id-conta ...

Code is not running in ReactJS

My challenge is to use canvas and script to draw a rectangle with one diagonal line. However, when I try to do so, only the rectangle appears on my browser. It seems like the script is not being executed. Here's the code: import React, { Component } ...

extract data from a JSON-formatted object

While developing my asp.Net application using MVC 3, I encountered a situation in which I was working with a jQuery control. I received a JSON response that looked like this: { "text":"Books", "state":"open", "attributes":{ ...

Is today within the current week? Utilizing Moment JS for time tracking

There is a problem that I am facing. Can you assist me in determining whether the day falls within the current week? I am currently developing a weather forecast service and need to validate if a given day is within the current week. The only clue I have ...

Divide the pair of arrays that are transmitted via JSON

I combined two arrays and passed them through JSON, as shown below: $result = array_merge($json, $json1); echo json_encode($result); Now, to retrieve the data, I am using the following code: $.getJSON('./tarefasaad52', function (data) { } How ...

Creating a user-friendly form in a Nuxt/Vue application that enables dynamic attribute creation

I am currently working on designing a form that enables users to create different variations for a product within a Nuxt/Vue application. The goal is to provide users with the ability to specify attributes for each variation using a text field. These attr ...

How can I incorporate arithmetic operators within a function in EJS?

Currently, I am developing an express app that includes a booking form using ejs with added functionality for payment processing. In the code, I have a select tag where the selected text is stored in a variable. Although console logging shows the value co ...

Tips for collapsing a child accordion when the parent accordion is collapsed?

Here is the code I have for a functional parent/child accordion div setup: <div class="accordion"> <h3>Part 1</h3> <div class="accordion"> <h3>Sub-Div1</h3> <div> <p>This ...

Retrieve information from subcategories in the Realtime Database using Firebase

Trying to access message inputs from ALL users has been a challenge. While it can be done for a specific user, the goal is to do so for all users by specifying in the code. Each UID is unique, adding complexity to the process. The Realtime Database struct ...

Enable the input field once the checkbox has been marked

Here is a checkbox example: <div class="form-group"> <input type="checkbox" id="examination" class="form-control" name="exam" placeholder="Enter Title"> <label>Enable Exam</label> </div> Additionally, I have a disabled inpu ...

Despite changes in the state they are set to, the InitialValues remain constant

I am facing an issue with a Semantic-UI modal that includes a redux-form as its content. The form is passed to the modal when it opens, and the form element has an initialValues prop mapped to state. <FormModal handl ...