Is it possible to modify the 3D object within WebGL using Three.js only in certain scenarios, such as adding textures or moving the mouse?

Utilizing a 3D object exported from Blender, specifically cylinder.obj, I have successfully implemented its rendering on the screen with the help of Three.js. The functionality to rotate the object using mouse input has also been integrated. This entire visualization is enclosed within a sizable div element measuring at 600x600 pixels.

The code snippet below outlines the render logic:

// Function that continuously renders the scene and updates it when necessary.
function animate() {
    // Render the scene.
    renderer.render(scene, camera);

    requestAnimationFrame(animate);
}

My current understanding suggests that this initiates a continuous loop where the object keeps getting rendered on the page repeatedly.

Is there a way to render the object only once in the scene and then refresh it solely upon modifications such as texture alterations or rotational adjustments triggered by mouse movements? Upon completion of these changes, I aim for the scene to remain static without utilizing excessive CPU resources for 3D rendering.

In essence, is there a method to trigger rendering only when required and maintain an idle state without significant CPU consumption when the scene functions akin to an image?

I am relatively new to three.js and conducting tests on this application primarily on Chrome and IE11. Kindly let me know if additional details are needed for clarification.

EDIT: Here is the complete JavaScript code provided:

// Global variables declaration
// Initialize the scene, camera, and renderer as global entities.
var scene, camera, renderer;
var WIDTH = $("#myDiv").width(),
    HEIGHT = $("#myDiv").height();

// Setting up the scene components.
function init() {

    // Creation of the scene along with setting its dimensions.
    scene = new THREE.Scene();
    // Generate a renderer and append it to the DOM.
    if (Detector.webgl)
        renderer = new THREE.WebGLRenderer({ antialias: true });
    else
        renderer = new THREE.CanvasRenderer(); 

    renderer.setSize(WIDTH, HEIGHT);
    renderer.domElement.id = 'mycanvas'; 
    console.log(renderer);
    $("#myDiv").append(renderer.domElement);

    // Establishing the camera perspective, positioning, and inclusion within the scene.
    camera = new THREE.PerspectiveCamera(45, WIDTH / HEIGHT, 0.1, 100);
    camera.position.set(-3, 4, 12);
    scene.add(camera);

    // Implementing an event listener for resizing the renderer alongside the browser window.
    window.addEventListener('resize', function () {
        var WIDTH = window.innerWidth,
            HEIGHT = window.innerHeight;
        renderer.setSize(WIDTH, HEIGHT);
        camera.aspect = WIDTH / HEIGHT;
        camera.updateProjectionMatrix();
    });

    // Defining the scene's background color.
    renderer.setClearColor(0x333F47, 1);

    // Incorporating point lights into the scene.
    var light2 = new THREE.PointLight(0xffffff);
    light2.position.set(0, 10, -10);
    scene.add(light2);

    var light3 = new THREE.PointLight(0xffffff);
    light3.position.set(1, 5, 10);
    scene.add(light3);


    // Loading the mesh model and adding it to the scene.
    var objLoader = new THREE.OBJLoader();
    objLoader.load('objects/male.obj', function (object) {
        object.position.y = 0;
        object.scale.x = object.scale.y = object.scale.z = 1;
        scene.add(object);
    });
}

// Rendering the scene and updating the display based on necessity.
function draw() {

    //requestAnimationFrame(draw);


    // Render the scene.
    renderer.render(scene, camera);
}

init();
draw();

Answer №1

Event-driven programming is the concept of taking action only after a specific event occurs.

For instance:

function OnMouseMove(evt) {
    // perform a transformation update on an object

    // once the update is complete, draw!
    draw();
}

function textureLoaded() {
    // celebration – the texture has loaded and it's time to draw
    draw();
}

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

Instead of drawing based on a timer, you draw elements only when necessary, such as after a mouse movement or when a texture finishes loading.

You can connect OnMouseMove to an event listener and use textureLoaded as a callback function in Three.js for handling texture loading.

P.S. It's actually the GPU that handles the drawing process, not the CPU.

Answer №2

Finally cracked the code by implementing start - stop animation feature for my event handling, thanks to this helpful link: How to prevent requestAnimationFrame from running continuously

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

Use various onChange functions for sliding toggle

I need assistance with a toggle app I'm developing that includes two slide toggles. Even though I have separate onChange() methods for each toggle, toggling one slide-toggle also changes the value of the other slide toggle. The toggle state is saved i ...

Encountering an error message stating "Unable to recognize property 'screen' of undefined" when incorporating Quasar components into a Storybook story

I seem to be encountering an issue when trying to render Quasar components in Storybook using Vue and Quasar. I have a suspicion that the story is not recognizing the Quasar tags. I followed the steps to set up the project from and then initiated npx sb i ...

Limiting the number of promises in AngularJS

My web application allows users to select multiple files using a file input. After the user selects the files, I upload them one by one through my REST API. However, in Internet Explorer, if the user selects more than 10 files at once, some of the requests ...

Using JQuery to find the nearest element and narrowing down the search to its child elements

In my program, I have 3 forms identified by form1, form2, and form3. Each form contains its own set of dropdown lists named drop1 and drop2, along with a submit button. When the submit button is clicked in any form, it checks which option was selected from ...

Encountering issues with Office.context.document.getFileAsync function

I am experiencing a strange issue where, on the third attempt to extract a word document as a compressed file for processing in my MS Word Task Pane MVC app, it crashes. Here is the snippet of code: Office.context.document.getFileAsync(Office.FileType.Co ...

I'm currently attempting to establish a connection between my server.js express API and MongoDB, but I keep encountering an unfamiliar error message that I'm having trouble decipher

Here is the server.js code: import express from 'express'; import bodyParser from 'body-parser'; import userRoutes from './routes/users.js'; import mongoose from 'mongoose'; co ...

Are there any publicly accessible Content Delivery Networks that offer hosting for JSON2?

Everyone knows that popular tech giants like Google and Microsoft provide hosting for various javascript libraries on their CDNs (content distribution networks). However, one library missing from their collection is JSON2.js. Although I could upload JSON2 ...

Tips for conducting remote testing with the help of WebARonARKit and three.ar.js

Currently working on creating an iPad app using WebARonARKit in combination with three.ar.js. Successfully managed to get the demo projects up and running on my iPad. Seeking advice on how to test my personalized code on my desktop browser while actively ...

Socket.io transmitting [object Object] containing data from a mongoDB document

Happy Thanksgiving to all! I hope everyone enjoys the delicious food on their plates. I know I definitely will! Anyway, I'm currently attempting to query my mongoDB collection for the latest inserted document and send it to the client. However, inst ...

Online Adventure - Saving Conversations

I am interested in developing an RPG using JavaScript. The game will involve a significant amount of dialog. While I have knowledge of PHP and MySQL, I am new to XML. My queries are: Would it be more efficient to store the dialog in a MySQL database and ...

Using Twig in combination with Ajax to send requests using the Get method

Trying to utilize the Get method to send an Ajax request, I have encountered an issue. Despite adding an alert to my request function to confirm the link, no alert is displayed! Here is my code: Below is my html.twig view: <a href="#" onclick="reques ...

The best practices for managing item spacing in React or React Native

I am facing some challenges while trying to adjust the spacing of my components. My goal is to have the grid occupy 90% of the screen, with the gear icon taking up the remaining 10% <View style={{ paddingLeft: insets.left, padding ...

Issues with three.js performance observed on iPad devices when screen width reaches 1024 pixels

My website utilizes three.js in conjunction with CanvasRenderer. The size of the renderer is dynamically adjusted based on the window size. However, when viewed on an iPad, the size is set to 1024 x 672 pixels, resulting in extremely poor performance at ap ...

Changes made in the view of a VueJS application are not being reflected in Laravel when using

Embarking on my first journey with VueJS within a Laravel PHP framework has been quite the adventure. A new project is on the horizon, and I dove in headfirst by making various changes, such as adding new elements and altering titles. However, much to my d ...

Notification does not appear once the full content of all iframes on the page has been loaded

<!DOCTYPE html> <html lang="en"> <head> <title> </title> <meta charset="utf-8" /> <link rel="stylesheet" type="text/css" href="css/custom.css" /> </head> <bo ...

Error encountered while trying to store a JSON object in local storage

When attempting to insert a JSON in localStorage, I am encountering the error Unexpected token ~ in JSON at position 3 during the parse process. Here is how I am inserting the data into localStorage: localStorage.setItem( "users", `"[\"~#iM& ...

Android Chrome users experiencing sidebar disappearance after first toggle

Over the past few days, I've dedicated my time to developing a new project. I've been focusing on creating the HTML, CSS, and Java layout to ensure everything works seamlessly. After completing most of the work, the design looks great on desktop ...

Is it better to use e.target instead of refs when testing?

I have been frequently creating components like this: <input ref="ckbx" type="checkbox" checked={this.props.checked} onChange={() => this.props.onChange(this.refs.ckbx.checked)} /> However, I recently realized that testing this is ...

Tips for fetching integer numbers in a string in JavaScript in sequential order starting from the left side

Within an input element, users are required to input the price of a product. <input size=10 type="text" id="prd_price" title="prd_price" name="prd_price"> Users have the ability to enter Currency Symbols along with other characters, and we cannot ...

The error message "ReferenceError: process is not defined" occurs when the 500 process is

Every time I try to import a library or use puppeteer, I keep encountering this problem and I'm not sure how to resolve it. My goal is to extract data from LinkedIn using https://www.npmjs.com/package/linkedin-client. Here's the simple code snipp ...