Blank Screen with Three JS Animation

I'm relatively new to three js and webgl. Currently, I'm working on a complex solar system project and everything seems to be functioning well until I attempt to animate anything. Below is a simplified version showcasing the issue (with a low resolution sun). As soon as I include the line sun.rotate.y += 1; the program refuses to load or execute anything. Despite searching extensively, I can't seem to pinpoint the problem. I'm convinced it's a minor oversight on my end. Thank you in advance for any assistance.

<script>

    // SETUP SCENE

    var camera, controls, scene, renderer;
    var container

    init();
    animate();

    function init() {

        camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 90000 );
        camera.position.z = 100;

        controls = new THREE.TrackballControls( camera );

        controls.rotateSpeed = 1.0;
        controls.zoomSpeed = .2;
        controls.panSpeed = 0.8;

        controls.noZoom = false;
        controls.noPan = true;

        controls.staticMoving = false;
        controls.dynamicDampingFactor = 0.3;

        controls.keys = [ 65, 83, 68 ];

        controls.addEventListener( 'change', render );


        scene = new THREE.Scene();


        // ADD THE SUN PHYSICAL LOCATION
        var geometry = new THREE.SphereGeometry(5, 3, 3, 0, Math.PI * 2, 0, Math.PI * 2);
        var material = new THREE.MeshBasicMaterial({color: "Yellow"});
        var sun = new THREE.Mesh(geometry, material);
        scene.add(sun);

        //RENDER
        renderer = new THREE.WebGLRenderer( { antialias: false } );
        renderer.setPixelRatio( window.devicePixelRatio );
        renderer.setSize( window.innerWidth, window.innerHeight );

        container = document.getElementById( 'container' );
        container.appendChild( renderer.domElement );

        window.addEventListener( 'resize', onWindowResize, false );

        render();
        animate();


    }

    function onWindowResize() {

            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();

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

            controls.handleResize();

            render();

    }

    function animate() {

            requestAnimationFrame( animate );

            controls.update();

            render();    
    }


    function render() {
            sun.rotate.y +=1; // Issue with animation?
            renderer.render( scene, camera );
    }

</script>

https://i.sstatic.net/qRkoQ.jpg

Answer №1

In order to make sun visible in the render() scope, it needs to be defined as a global variable.

It seems that to rotate a mesh, you should use methods like "rotateX(), rotateY(), or rotateZ()". So, the correct syntax would be sun.rotateY(0.01)

Update: A better way to rotate the mesh is by modifying its rotation property instead of using the rotate property.

Answer №2

If you're working with ES6 or ES5, scope issues can be tricky to navigate. The problematic parts are as follows:

Make sure to declare your variables globally (or else JavaScript will add them to the global space):

var container, sun;

Then, reference them inside the init function:

this.sun = new THREE.Mesh(geometry, material);

Check out the Working Pen for a solution:

Dealing with Scope Issues in Three.js

Additionally, keep in mind that TrackballControls is not integrated into Three.js by default - you'll need to import it separately, as shown in the pen.

Another tip for rotation:

sun.rotation.y += 0.003;

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 reason behind my titles being triple the length they should be?

Here is my personal website The titles are appropriately set for the About College section Note: Utilizing Purl library for this purpose var seg2 = ''; if (url.segment(2) == 'college-life') seg2 = "College Life"; else if (url.seg ...

Style the code presented within a div tag

I am in the process of creating a JavaScript-powered user interface that can generate code based on user interactions. While I have successfully implemented the code generation functionality and saved the generated code as a string, I am facing difficultie ...

Automatically Adjust Text Size to Fit Input Forms using jQuery

Does anyone know how to use jQuery to dynamically change the font size in a form input field so that it always remains visible and fits even as the user types more text? I want the font size to start at 13px and progressively shrink as the text reaches the ...

Analyzing an array through its sub arrays

Imagine we are dealing with an array of varying length and we need to process it in chunks of maximum size 100, aiming to use the fewest number of chunks. For example, if the array's length is 241, we would need to divide it into 3 subarrays: 41, 100, ...

Tips for effectively packaging the React 17 library alongside the latest JSX transformation feature as an ES Module

I am currently in the process of creating a basic library consisting of React components that I intend to publish as an ES Module package for NPM. With the utilization of React 17, I have incorporated the new JSX transform into my code. To generate the ES ...

The error message "Uncaught TypeError: Unable to retrieve the 'lat' property of an undefined object when serializing leaflet data using $.param()" is displayed

Being a complete novice in JavaScript, I am experimenting with posting user location and map bounds using Leaflet and an AJAX call. While my event handler stateUpdater.onLocationFound successfully logs the user coordinates and map bounds, I encounter an is ...

Accessing HTML elements that are created dynamically in AngularJS

I am facing an issue where I cannot access a function within a newly created DOM element. Despite my best efforts, I can't seem to figure out what is causing this problem. $scope.createCustomHTMLContent = function(img, evtTime, cmname, evt, cust, ser ...

Seeking assistance with exporting a Vue single file component that relies on Swiper.js for functionality

I'm having trouble figuring out how to properly export a Vue SFC that includes the mySwiper object. I would appreciate seeing an example from someone who has experience with this. Below is the JavaScript portion of my SFC <script> import Swiper ...

Is there a way to use Javascript to determine if a string within a JSON object has been altered?

I am looking for a way to continuously monitor changes in a specific string or date stored in a JSON file. How can I effectively store this value and create a mechanism to compare it for any differences? Any assistance would be highly appreciated. // Ex ...

Ways to resolve the issue of BrowserWindow not being recognized as a constructor when trying to create a child window within the Electron

Currently, I am utilizing electron to construct an application with two windows. In my attempt to open a second window from the renderer process, I have implemented the following code snippet: const electron = require('electron'); const BrowserW ...

A comprehensive guide on creating translation files using grunt angular-translate from original JSON files containing translations

I have a unique angular application that requires support for multiple languages. To achieve this, I have implemented the angular translate task in the following manner. My goal is to create separate language files which can be loaded later using the useSt ...

The modifications made to a bound value in AngularJS directives do not propagate to the outside components

I've been experimenting with bound variables inside directives, but I'm facing an issue where the view doesn't seem to refresh. Despite the model updating correctly (as seen in the console log) and calling $apply(), the view remains unchange ...

Interactive Canvas Feature: Drag and Drop Across Various Objects in HTML 5

I have developed a custom code that enables the creation and rendering of objects on an HTML5 canvas. class Rectangle extends Shape { constructor(options, canvas, type = 'rectangle') { super(...); // inherited from the super class thi ...

React - a search feature for array filtering

Lately, I've been delving into the intricacies of implementing a live search input that interacts with an array to create a file tree. Here is where you can find all the code: https://codesandbox.io/s/815p3k3vkj Although the solution seemed straightf ...

What are the issues with the latest API routing in Next.js?

I am encountering an error that says: SyntaxError: Unexpected token s in JSON at position 0 Here is my code: import { PrismaClient } from '@prisma/client'; import { IDPay } from 'idpay'; import { NextResponse } from 'next/server&ap ...

Why is the function app.get('/') not triggering? The problem seems to be related to cookies and user authentication

Need help with app.get('/') not being called I am working on implementing cookies to allow multiple users to be logged in simultaneously. Currently, users can log in successfully. However, upon refreshing the page, all users get logged in as the ...

Changing the name of '_next' to 'next' within the output folder: NextJS

While developing my NextJS chrome extension, I encountered an issue when trying to 'load unpacked' extension. An error message popped up stating that "Cannot load extension with file or directory name _next. Filenames starting with _ are reserved ...

In the virtual playground of Plaid's Sandbox, how can I replicate a fresh transaction and detect it using the Webhook feature?

Is there a way to trigger a simulated transaction within the webhook instead of just a DEFAULT_UPDATE event? I'm trying to find a way to simulate an actual transaction so that I can test my webhook integration. I've searched through the sandbox ...

Ways to show alternative data from a database in Laravel 8

I am working on a project where I need to display additional data based on the option selected from a dropdown menu populated from a database. Can anyone guide me on how to achieve this using javascript or jquery? https://i.stack.imgur.com/k3WLl.png Belo ...

Unexpected behavior when using JQuery's .load() method

In my HTML code, I have a main div element with child elements as lists. These lists are dynamically populated with data from the server and each item in the list has a checkbox. When a checkbox is checked, I want that item to move to the bottom of the lis ...