Resizing the window triggers a speed up in the animation on ThreeJS

After examining the code below, I noticed that as the window is resized, the speed seems to increase rapidly. Can anyone explain why this is happening?

        <!DOCTYPE html>
        <html>
        <head>
        <title>Page Title</title>
        </head>
        <body>

        <h1>FooBarBaz</h1>
        <p>LaDeDa</p>
        <script src="http://threejs.org/build/three.min.js"></script>
        <script src="https://threejs.org/examples/js/controls/TrackballControls.js"></script>
        <script>
        var scene = new THREE.Scene();
        var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );

        var renderer = new THREE.WebGLRenderer();
        renderer.setSize( window.innerWidth, window.innerHeight );

        var objects = [
            {
                name : "earth",
                mesh : new THREE.Mesh(new THREE.SphereGeometry(1, 32, 32), new THREE.MeshPhongMaterial()),
                init : function(scene){
                this.mesh.position.set(0,0,0);
                //this.material.map = THREE.ImageUtils.loadTexture('../earth.jpg');
                scene.add(this.mesh);
                },
                animate : function(t){return}
            },
            {
                name : "satellite",
                mesh : new THREE.Mesh(new THREE.SphereGeometry(0.1, 32, 32), new THREE.MeshPhongMaterial()),
                init : function(scene){
                this.mesh.position.set(1.5,0,0);
                //this.material.map = THREE.ImageUtils.loadTexture('../earth.jpg');
                scene.add(this.mesh);
                },
                animate : function(t){this.mesh.position.set(Math.sin(t)*1.5,Math.cos(t)*1.5,0);}
            }];
        objects.forEach(object => object.init(scene));

        var light = new THREE.HemisphereLight(0xf6e86d, 0x404040, 0.5);
        scene.add(light);

        camera.position.x = 0;
        camera.position.y = -5;
        camera.position.z = 0;
        camera.lookAt(new THREE.Vector3( 0, 0, 0));
        var timeStep = 0.01;
        var time = 0;
        var controls = new THREE.TrackballControls( camera, renderer.domElement );
        controls.target.set( 0, 0, 0 );
        var render = function () {
            time += timeStep;
            requestAnimationFrame( render );
            objects.forEach(object => object.animate(time));
            controls.update();
            renderer.render(scene, camera);
        }
        function onWindowResize() {
            camera.aspect = window.innerWidth / window.innerHeight
            camera.updateProjectionMatrix()
            renderer.setSize(window.innerWidth, window.innerHeight)
            render()
        }
        window.addEventListener('resize', onWindowResize, false)

        document.body.appendChild( renderer.domElement );
        render();</script>
        </body>
        </html>
        

It appears that each resize of the window causes a rapid acceleration in speed... What could be causing this behavior?

Answer №1

As the resize function triggers the render function, and render function in turn calls requestAnimationFrame(render), it causes multiple recursive loops of render functions overlapping. To resolve this issue, a new function called renderOnce was introduced which does not request animation frame. This helps in solving the problem of multiple overlapping renders. Although the animation may appear to move slightly faster during resizing, once the resizing is complete, the animation speed returns back to normal.

    var renderOnce = function () {
        time += timeStep;
        objects.forEach(object => object.animate(time));
        controls.update();
        renderer.render(scene, camera);
    }
    var render = function () {
        renderOnce();
        requestAnimationFrame( render );
    }
    window.addEventListener('resize', onWindowResize, false)
    function onWindowResize() {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderOnce();
    }

Furthermore, the issue of acceleration during resizing can be resolved by moving time+=timeStep from renderOnce to render.

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

Incorporate a `fresh Audio` element into my redux repository

I'm attempting to include a new Audio element in my redux store. This is how my reducer appears: export const songsReducer = (state = {}, action) => { switch (action.type) { case "PLAY_SONG": return { ...state ...

Is there a way to eliminate the legend symbol for just one legend in Highcharts?

Looking to customize a legend in Highcharts but facing limitations due to Plot Lines and Bands not having legends. To work around this, I have added an empty series that acts as a toggle for showing/hiding plot lines. Since my plot lines are vertical, I im ...

The rule 'react-hooks/exhaustive-deps' does not have a defined definition

I received an eslint error message after inserting // eslint-disable-next-line react-hooks/exhaustive-deps into my code. 8:14 error Rule 'react-hooks/exhaustive-deps' definition not found I tried to resolve this issue by referring to this p ...

Is it possible to transmit a WebRTC frame to a Python script?

I recently built my first web app using Python and Django, which displays webcam frames of clients. 'use strict'; // For this project, I am only streaming video (video: true). const mediaStreamConstraints = { video: true, }; // Video element ...

Generating Bootstrap carousel items dynamically using JavaScript

One of my recent achievements includes creating a webpage that displays a list of loaded data, some of which contain YouTube links. I am currently facing a challenge in trying to showcase these videos in a bootstrap carousel due to the complexity of integ ...

The Javascript and CSS code for a button fails to trigger the animation function after the initial click

Is it possible to trigger the animation function multiple times after the initial click without making changes to the HTML code? The ID and class in the code must remain as they are. I attempted to use the display property set to none, but it did not yie ...

Is it possible to set a read-only attribute using getElementByName method

To make a text field "readonly" by placing JavaScript code inside an external JS file, the HTML page cannot be directly modified because it is located on a remote server. However, interaction can be done by adding code in an external JS file hosted on a pe ...

Guide on creating a similar encryption function in Node JS that is equivalent to the one written in Java

In Java, there is a function used for encryption. public static String encryptionFunction(String fieldValue, String pemFileLocation) { try { // Read key from file String strKeyPEM = ""; BufferedReader br = new Buffer ...

Discovering the initial element with a data attribute above zero using JQuery

I am working with a set of divs that have the class .item-wrap. At the moment, I am able to select the first div using this code snippet: $(".item-wrap:first").trigger( "click" ); Each .item-wrap element comes with a data-amount attribute. My challenge ...

Is there a way to use JavaScript to determine if GEARS is already installed on a system?

Does the existence of windows.gears not equal to undefined or what??? I am simply looking to use javascript to determine true or false based on whether the person has google Gears installed. ...

Issue with Jquery Drag and Drop functionality, navigate to a different page

I am trying to incorporate a page with js from quotemedia.com using Jquery. When I insert the js into the sortable, and then drag and drop the element containing the js, it suddenly switches to full page display. This issue occurs in Firefox, but IE works ...

Achieving checked checkboxes based on already selected values in AngularJS

function Test1Controller($scope) { var storeid = window.localStorage.getItem("storeid"); var serverData = ["Samsung Galaxy Note", "Samsung Galaxy S6", "Samsung Galaxy Avant","Samsung Galaxy Young"]; $scope.items= [] ; var selectedvalue="Samsu ...

The issue persists with the addEventListener function not working multiple times

My issue is that the addEventListener function is only working for the 'scroll' event and not for 'addMoreFields' or 'removeFields'. If I move the scroll section down, then it works for 'addMoreFields' and 'remo ...

Using Highstock for Dynamic Data Visualization in Web Applications

Looking to create a chart using data from a MySQL database that includes timestamps and temperature readings. The timestamp format is '2015-06-11 22:45:59' and the temperature is an integer value. Unsure if the conversion of the timestamp to Java ...

Is there a way to set columns as initially hidden in MaterialTable?

I have a MaterialTable with many columns, and some of them are not always necessary to display. I am looking for a way to hide these columns unless the user specifically selects them. I attempted to use the hidden: true property in the column configuratio ...

Is it feasible to invert the order of arguments in async.apply?

According to the async documentation: apply(function, arguments..) Creates a function continuation with certain arguments already applied. This can be useful when combined with other control flow functions. Any additional arguments passed to the returned ...

React fails to display image on the server

One issue I'm facing with my React project on the server is that some images are not being displayed. Click here to view image description The console error message reads: ASGimagen.png:1 GET https://[url of my server]/autodiagnostico/cuadroanimado ...

Generate a randomly structured 2D array called "Array" using JavaScript

Can anyone help me with extracting a random array from a 2D named array? I've tried several solutions but none of them seem to work. var sites = []; sites['apple'] = [ 'green' , 'red' , 'blue' ]; sites['o ...

Is it possible to simultaneously toggle buttons and submit a form?

I am currently working on a functionality that involves toggling the display of two buttons and submitting a form. Code toggleButtons() { var btn1 = document.getElementById("start"); var btn2 = document.getElementById("pause"); if (btn1.style. ...

What methods are available for managing model fields within a for loop in Django?

As a newcomer to Django, I am embarking on the journey of creating a Quiz web application that presents one question at a time. Upon selecting an answer using radio buttons, the application should promptly display whether the response is correct or incorre ...