Create a static cube in Three.js

Recently, I started exploring Three.js and my goal was to create a static cube. I came across an example of a rotating cube which I used as a reference:

var camera, scene, renderer;
var mesh;

init();
animate();

function init() {

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

    scene = new THREE.Scene();
    var texture = THREE.ImageUtils.loadTexture( '16.jpg' );
    var geometry = new THREE.BoxGeometry( 200, 200, 200 );
    var material = new THREE.MeshBasicMaterial( { map: texture } );
    var axes = new THREE.AxisHelper( 20 );

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

    renderer = new THREE.WebGLRenderer();
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

}

function animate() {

    requestAnimationFrame( animate );

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

    renderer.render( scene, camera );

}

After successfully creating the rotating cube, I decided to make a static cube by simply removing the rotation code:

var camera, scene, renderer;
var mesh;

init();
renderer.render( scene, camera );

function init() {

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

    scene = new THREE.Scene();
    var texture = THREE.ImageUtils.loadTexture( '16.jpg' );
    var geometry = new THREE.BoxGeometry( 200, 200, 200 );
    var material = new THREE.MeshBasicMaterial( { map: texture } );
    var axes = new THREE.AxisHelper( 20 );

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

    renderer = new THREE.WebGLRenderer();
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

}

However, all I see is a black screen now. What could be causing this issue?

Answer №1

The loading of textures is performed asynchronously, and it seems that you are attempting to render the scene before the texture loading process is complete. To address this issue, consider adding a callback function to the Image Loader and triggering the render again:

var texture = THREE.ImageUtils.loadTexture('16.jpg', undefined, function () {
    renderer.render(scene, camera);
});

Another approach is to continuously render using requestAnimationFrame:

init();
animate();

//...

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

Answer №2

After removing animate(), the call to

renderer.render( scene, camera );

was also removed. Make sure to include this in your code again to properly render the scene.

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

Using Titanium for Android to Display High-Quality Images

My goal is to showcase a high-resolution image (minimum size of 2000x2000) on an Android device using Titanium, allowing users to scroll around it similar to a scroll view on iOS. However, I am aware that Android does not offer the same type of scroll view ...

Steps to bring life to your JavaScript counter animation

I need to slow down the counting of values in JavaScript from 0 to 100, so that it takes 3 seconds instead of happening instantly. Can anyone help me with this? <span><span id="counter"> </span> of 100 files</span> <s ...

Utilize AJAX to accurately capture and handle error codes

Here is a snippet of code that I want to send to my server: $.ajax({ type: 'POST', url: 'post.php', data: { token: '123456', title: 'some title', url: 'http://somedomain.com', data: & ...

Troubleshooting Test Failures: The importance of passing $controller in the callback of 'it' function in Angular

As a newcomer to testing, I am attempting to write Jasmine/Karma tests for a controller. Given a sample test to use as a starting point, the issue arises when passing the $controller in the argument of the it block. The test passes successfully with this s ...

Variations in output observed from angular function across various sections within DOM

After fetching a list of permissions in the background, my goal is to display a page or an error message based on whether the user has the required permissions. I encountered an unusual issue where both sections of the page are being displayed despite hav ...

How to use JavaScript and regex to control the state of a disabled submit button

I have a challenge where I need to activate or deactivate a submission button in a form called btn-vote using JavaScript. The button will only be activated if one of the 10 radio buttons is selected. Additionally, if the person-10 radio button is chosen, t ...

Guide to displaying API data in HTML format

This university assignment involves working on a homework project where I need to utilize a public API in HTML. So far, I have successfully called the public API to display a list of radio channels in the left menu (without adding any click functionality). ...

Begin the NextJS project by redirecting the user to the Auth0 page without delay

I am new to coding and currently working on a project using Typescript/NextJS with Auth0 integration. The current setup navigates users to a page with a login button that redirects them to the Auth0 authentication page. However, this extra step is unneces ...

Adjust the DOM based on the output of the function

I'm currently working on creating a list where only one element can be active at a time. The state is updating correctly, but I'm facing an issue with the isActive function. It only activates initially and doesn't trigger when the state chan ...

How to access an array using a variable with the same name in JavaScript?

Possible Duplication: Retrieve variable from string I am facing a scenario where I have an array named myArray and a variable called myVar. The value stored in myVar is 'myArray', which happens to be the name of the array. Is there a way to ...

Steps for executing Mocha tests in a specified sequence

Background Currently, I am developing a Node.js program where I am creating test suites in Mocha using Chai and SinonJS. The program involves a core graphics module that manages access to a node-webgl context. Due to the nature of node-webgl, I want to i ...

Issues with External JavaScript Functionality in MVC 4

To better illustrate my issue, I have created a sample code snippet that showcases the problem. Here is the original code used in the view: @model MyProject.Web.UI.ViewModels.MyModel @{ ViewBag.Title = "Test"; } @section scripts{ <script> ...

Ways to change the chart type in ApexCharts

I'm seeking a way to change the chart type of an existing ApexCharts that has already been rendered. After reviewing the methods, I attempted to use the updateOptions() method, but encountered the error: Uncaught TypeError: Cannot read property &apos ...

Go to a different webpage containing HTML and update the image source on that particular page

I am facing an issue with my html page which contains multiple links to another page. I need to dynamically change the image references on the landing page based on the link the user clicks. The challenge here is that the link is inside an iframe and trigg ...

Preventing users from selecting past dates in HTML input date field

I need help with disabling past dates in an HTML date input field. Even though I am able to restrict selecting past dates on the date picker, I can still save data if I manually type in a previous date (e.g., 12/08/2020). $(document).ready(function() { ...

"Searching for existing data in MongoDB upon click event from the client side: A step-by-step guide

I have developed an express app that allows users to search for movies and add them to lists. If a movie is already added to the list, I want to show 'Already added' instead of 'Added to list'. How can I achieve this functionality from ...

Issue with the bootstrap toggle menu script not functioning as expected

My toggler menu is not working and I'm not sure why. I'd also like to know which links to remove and how to improve my website's speed. When I resize the browser window, the toggle menu icon is not displayed correctly and does not open a new ...

Error encountered when trying to update Express Mongoose due to duplicate key

In my MongoDB database, I have a unique field called mail. When attempting to update a user, I encounter an issue where if I do not change the mail field, it triggers a duplicate key error. I need a solution where it is not mandatory to always modify the ...

When Gulp is executed it throws an error that is not handled: `error` event is unhandled

Check out the code below: main.js var React = require('react'); var App = require('./components/app.js'); React.render( <App />, document.getElementById('container') ); app.js var React = require(' ...

jQuery problem causes page to scroll when button is clicked

Is there a way to smoothly scroll to the second section of the page when a button is clicked using jQuery? $('.home_scroll_btn a').on('click', function(){ var scrollPosition = $('#intro-home').offset().top; $( ...