Tips for minimizing the CPU and GPU load in three.js within a web browser

Currently, I have a rotating animated globe with randomly changing colored dots. While it functions properly, leaving it running in the background significantly slows down my laptop. Are there any optimizations I can implement to reduce its memory usage?

Upon checking the task manager in Chrome, I noticed that it consumes 12% CPU and 128MB of GPU memory when the tab is active. Is this normal for three.js, or should I consider modifying the code?

    ngAfterViewInit() {
    if(this.enabled) {
        this.controls = new OrbitControls(this.camera, this.renderer.domElement);
        this.controls.rotateSpeed = 0.5;
        this.controls.enableDamping = true;
        this.controls.dampingFactor = 0.5;
        this.controls.rotationSpeed = 0.3;
        this.controls.enableZoom = false;
        this.controls.autoRotate = true;
        this.controls.autoRotateSpeed = -1;

        this.renderer.setSize(window.innerWidth, window.innerHeight);
        this.rendererContainer.nativeElement.appendChild(this.renderer.domElement);
        this.animate();
        const timerId = setInterval(() => this.updateColor(), 650);
    }
}

private get enabled(): boolean {
    if(this._enabled!==undefined) {
        return this._enabled;
    }
    const canvas = document.createElement("canvas");
    const gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
    this._enabled = gl && gl instanceof WebGLRenderingContext;
    return this._enabled;
}

private initGlobe(): void {
    // Original initialization code here
}

animate() {
    // Original animation code here
}

nextAnimation() {
    // Original next animation code here
}

updateColor() {
    // Original color update code here

I have looked into suggestions about merging meshes from other questions, but I am unsure if that would be effective in this case. Thank you!

Answer №1

What do you mean by "background"? That can make all the difference.

If by "background," you're referring to not being the front tab, then using requestAnimationFrame will cause the browser to stop sending animation frame events when your page is not in focus or if you minimize the browser window.

However, if by "background" you mean the front tab but not currently in focus, you can utilize the blur and focus events to pause the page entirely.

For instance, keep in mind that NOTE: blur events may not function within an iframe as shown below, but should work when copied into a separate file

let requestId;

function start() {
  if (!requestId) {
    requestId = requestAnimationFrame(animate);
  }
}

function stop() {
console.log('stop');
  if (requestId) {
    cancelAnimationFrame(requestId);
    requestId = undefined;
  }
}

const ctx = document.querySelector("canvas").getContext('2d');

function animate(time) { 
  requestId = undefined;
  
  ctx.save();
  ctx.translate(
    150 + 150 * Math.cos(time * 0.001), 
     75 +  75 * Math.sin(time * 0.003),
  );
  ctx.scale(
     Math.cos(time * 0.005), 
     Math.cos(time * 0.007),
  );
  ctx.fillStyle = `hsl(${time % 360},100%,50%)`;
  ctx.fillRect(-50, 50, 100, 100);
  ctx.restore();
  
  start();
}

start();

window.addEventListener('blur', stop);
window.addEventListener('focus', start);
body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
<canvas></canvas>

Instead of halting on blur, consider implementing manual throttling such as rendering every 5th frame or reducing the number of elements rendered to optimize performance.

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

Trouble with displaying my three.js 3D model

I've tried multiple solutions I found, but none have fixed the issue of not being able to display 3D models. Many have suggested that it could be a problem with the camera, but so far I haven't been able to resolve it. Any assistance would be gre ...

Leveraging three.js JSONLoader

Having trouble getting imported models to show up in my three.js scene. The geometry is correct, but the model isn't visible regardless of the material applied. Since I am new to WebGL, I find it challenging to pinpoint the issue, but my suspicion is ...

Continue iterating using (forEach, map,...) until the object (children) has no more elements

I need to disable the active status for all elements within my object structure. Here is an example of my object: const obj = { name: 'obj1' , ative: true , children: [ { name: 'obj2' , ative: true , children: ...

Retrieving information from the sessionStorage within app.module.ts

During the initialization of my application, it automatically redirects to the Login component. Here, I collect user data (username and password) and upon clicking the "Sign In" button, I send this information to the server. Upon receiving the Authorizatio ...

How can I modify the glare effect of a Light in Three.js?

I am looking to enhance the glare effect on my Light (currently using PointLight). Is there a way to make it cast on a larger portion of the Plane rather than just a small location? https://i.sstatic.net/mKmee.png ...

Retrieve the variable only once a response has been received from the POST request

Is there a way to update a variable in my component only after receiving a response from a POST request? Here is the code in component.ts: formSubmit() { this.sent = this.submitProvider.sendByPost(this.form); this.formSent = this.submitProvider.f ...

Having difficulty importing a .glb file in Three.js with the import.meta.url method when using the parcel bundler

Greetings! I recently embarked on creating a fun little game using Three.js for me and my friends. After watching numerous tutorials on how to import .gltf and .glb files, I decided to use the parcel bundler with the command: npx parcel ./src/index.html to ...

Opacity levels for AM5 chart columns

Currently, I am attempting to create a gradient opacity effect on my plot. Unfortunately, I am facing difficulty in targeting the opacity of each column individually, as I can only seem to adjust it by series. serie.columns.template.setAll({ ...

Steps for transitioning from a mapped type to a discriminated union

Forgive me if this question has already been posed. I made an effort to search for a solution, but it seems I may not be using the correct terms. The issue arises with this particular structure. It involves a simple mapped type: type Mapped = { squ ...

Is it possible to create a prototype function within an interface that can group items in an array by a specific property, resulting in an array of objects containing a key and corresponding array of values?

I've been working on this code snippet and I'm trying to figure out how to make it work: Array<T>.groupBy<KeyType> (property): {key: KeyType, array: Array<T> }[]; The code looks like this: type ArrayByParameter<T, KeyType = ...

Jest came across a surprising token that it wasn't expecting while working with React and TypeScript in conjunction with Jest and React-testing-L

An unexpected token was encountered by Jest while using React and TypeScript along with Jest and React-testing-Library. Error occurred at: E:\Git\node_modules@mui\x-date-pickers\internals\demo\index.js:1 ({"Object." ...

How can one safely determine if a file is application/pkcs7-mime or similar in an Angular environment?

Can someone share a reliable way to identify application/pkcs7-mime or similar file types? Although one option is to check the final extension of the file, I am interested in learning about more effective methods. One approach mentioned in my research invo ...

OneGraph and Graphql Codegen produce enums with numerical representations

After migrating my project's codebase from using the direct Headless Wordpress GraphQL endpoint to OneGraph for Google+Facebook Business support, I encountered an error related to apollo referencing the output codegen. Here is the specific error messa ...

Creating multiple charts with Chart.js in an Angular component is a breeze

Working on an Angular 6 Project, I have a Component that receives a tile Object from its parent. The goal is to generate a Chart using chart.js for each passed tile. The issue is that only the first Chart gets rendered successfully, while the rest fail wit ...

Set an enumerated data type as the key's value in an object structure

Here is an example of my custom Enum: export enum MyCustomEnum { Item1 = 'Item 1', Item2 = 'Item 2', Item3 = 'Item 3', Item4 = 'Item 4', Item5 = 'Item 5', } I am trying to define a type for the f ...

Oops! Something went wrong - it seems like there was an issue trying to access the property 'Date/Heure' of

When my web application uploads a .mes file, it retrieves data and manipulates it to insert into an Object. Initially, the object is empty, but after uploading the file, the data appears. I am trying to display the 'date' obtained from the .mes ...

Three.js - Object facing perpendicular to path while traveling at 90-degree angle

In my concept, a square room is depicted where an object moves smoothly from corner to corner. The camera follows the object, facing the walls at all times but curving around in such a way that it maintains a continuous transition between walls without bei ...

Why does my array seem to update only once in the view?

I am currently working on a project that aims to visually represent sorting algorithms, but I have encountered an issue. In order to effectively visualize the sorting process of an algorithm, it is crucial to display every change in the array as the proc ...

Angular RxJS: The never-ending reduction

I have developed a component that contains two buttons (searchButton, lazyButton). The ngOnDestroy method is defined as follows: public ngOnDestroy() { this.unsubscribe$.next(); this.unsubscribe$.complete(); } I have created two observables from ...

What is the syntax for creating multi-line function definitions in TypeScript?

When it comes to writing functions with numerous parameters, do you typically format them like this: function foo( a: number, b: string, c: boolean): boolean { .... } or do you prefer formatting them like this: function foo( a: number, ...