Tips for optimizing the performance of a sine wave animation

After experimenting with JavaScript, I've managed to create a visually appealing sine wave animation but it's causing performance issues due to the high number of vectors being generated.

My current setup involves utilizing the p5js library. Below is a snippet of my progress so far. Are there any ways to optimize this for better performance without compromising on detail and smoothness?

        function setup () {
            let size = Math.min(windowWidth, windowHeight) * 0.96;
            size = Math.floor(size);
            createCanvas(windowWidth, windowHeight);
            noiseSeed(Math.random() * 50);
            frameRate(25); 
            noFill();
        }

        function windowResized () {
            let size = Math.min(windowWidth, windowHeight);
            size = Math.floor(size);
            resizeCanvas(windowWidth, windowHeight);
            noiseSeed(Math.random() * 50);
            frameRate(25); 
            draw();
        }

        function draw () {
            clear();
            beginShape();


            const _o = millis() * 0.0005;
            const amount = 20;
            const ampl = (630 / (windowHeight) * 100) + 120;

            for(var k=0; k<amount; k++) {

                beginShape();

                const offset = (1 - k / amount) * 3;
                const detail = 10;

                for(var i=0; i<(width+detail); i+=detail) {

                    let y = height * 0.5;
                    y += Math.sin(i * 0.01 - _o + (k / 50) + offset) * ampl;
                    y += Math.sin(i * 0.005 - _o + 5 + offset + noise(50)) * ampl;
                    console.log(i,y);
                    vertex(i, y);

                }
                stroke(255, 255, 255, (k/(amount - 1) * 100));
                frameRate(25); 
                endShape();
            }
        }

Codepen example: https://codepen.io/craiell/pen/zYGbLKm

Currently, I'm relying on the P5js library for this project. However, I am willing to explore other libraries or methods for optimization. Any suggestions or tips would be highly valued.

Answer №1

Eliminate the console.log statement within the nested loops. This adjustment results in a seamless animation experience on my laptop, even when I boost the frame rate to 60.

While I'm still learning P5js, it seems like the excessive invocations of frameRate() are not required for this scenario.

Answer №2

Here are some solutions that come to mind:

  1. To improve performance, consider replacing for() loops with foreach() or map()

  2. Explore using requestAnimationFrame() for smoother animations

  3. Create a cache of reusable vector coordinates to reduce the processing load from floating-point operations

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

Sticky header/navigation bar implementation in React Native for consistent navigation across views

Currently, I am working on creating a consistent navbar/header for my React Native app. At the moment, when I switch between views in my code, the entire interface changes. It functions properly, but the navbar/header scrolls along with the view, making i ...

Reversing text in mongodb

https://i.sstatic.net/Y61ML.png In my node.js and MongoDB 5 project, I am attempting to retrieve data where the field "TOTAL DUE" has a value other than '$0.00'. I have successfully selected records where "TOTAL DUE" equals '$0.00' usi ...

Is there a way to assign a unique scrollTop value for a specific scrollspy location?

I have a custom script that tracks the current position within a menu and applies an active class to it. However, I require specific rules for the ID contact_form. Specifically, I need to add 1000px to the scrollTop value for that particular ID location. ...

Loop through a non-array or non-object / handling both arrays and non-arrays equally

Sometimes, I find myself needing to handle arrays and single objects in a similar manner. For instance, I may have an object property that can be either an array or just a string (like the scale property): [ { "name": "Experiment type14", "id": ...

Understanding the concept of for loops in JavaScript and incorporating them in CSS styling

Hello there! I initially used this code to draw 12 lines, but now I am looking to incorporate a for loop and implement it in CSS. Can someone please guide me on how to proceed? <!DOCTYPE html> <html> <head> <style> #straigh ...

Tips for accessing basic information from these websites without encountering CORS issues

Having issues retrieving data from the following two sites: and Eurolottery. The CORS issue is causing the problem, and I was able to retrieve data using a Chrome CORS extension and the provided code below: var HttpClient = function() { this.get = fu ...

Having difficulties injecting a Service into a TypeScript Controller

I recently started working with TypeScript and I created a controller where I need to inject a service in order to use its methods. However, I am facing an issue where I am unable to access the service functions and encountering an error. Error TypeError ...

Discover the best practices for utilizing the npm commands.test function

Looking to create a function that can return the output from running npm test. (this function can be called as npm.commands.test(packages, callback) here) Attempted to use it in this way: var npm = require("npm"); npm.load('', function(err, np ...

Achieve horizontal wrapping of div elements

Currently, I am developing a blog where search results for articles will be displayed within divs. The design of the website is completely horizontal, meaning that articles scroll horizontally. Creating a single line of divs is straightforward, but it&apo ...

Chrome on IOS: Experiencing screen freezing while scrolling

1) I'm working with Material UI in React JS. I have added a simple scrollable code, but when I reach the bottom of the screen/scroll, it freezes. 2) I also tried it with a simple HTML page and it worked correctly. <div style={{ ...

Storing values in an array when checkboxes are selected within an ng-repeat loop in AngularJS

I am facing a situation where I need to populate an array with values when a checkbox is checked within an ng-repeat iteration. <li ng-repeat="player in team.players"> <div class="row"> <div class="col-md-3 m-t-xs"> <inp ...

transferring a document using axios, bypassing the FormData interface

One way to upload a file to the server is by using axios along with the FormData api. Here's an example: persist(photo){ let data = new FormData(); data.append('photo', photo); axios.post(`/api/photos/${this.user ...

Ensure that the footer remains at the bottom of the page without being fixed to the bottom

I am currently working on configuring the footer placement on pages of my website that contain the main body content class ".interior-health-main". My goal is to have a sticky footer positioned at the very bottom of these pages in order to eliminate any wh ...

JavaScript Async Ordering

I have a specific question regarding asynchronous operations in Javascript. I am currently building a Node.js API to interact with an OrientDB database, using the Node-orient package for basic connectivity functions. Some of these functions are as follows: ...

What is the best way to arrange the keys of a JavaScript object in a customized

I am struggling to find a way to custom sort a JavaScript object properly. For example, I have the following object: var test = { 'yellow': [], 'green': [], 'red': [], 'blue': [] } And an array with values ...

How can we enhance the backbone sync feature by appending a query string to the URL?

I am facing an issue with adding a token to the backbone URL query string and I am seeking assistance from you all. Here are three important things to note: There is a REST API that requires a token for each request An NGINX backend handles authenticatio ...

Creating a unique Angular JS / Material / Datatables application - Proper script loading sequence required based on page context

My top two declarations placed above the closing body tag. When used in a material dropdown page, the current order of these scripts works fine. However, when I switch to my datatables page (which is a separate page), I need to swap the order of the two s ...

Do these two JavaScript statements behave the same under the principles of functional programming in a React environment?

Is there a rule in functional programming that states these two approaches are equivalent? When working on a React application, I initially passed a function as an attribute using the second version where the first parameter is also passed. Out of curiosi ...

Utilizing the 'PUT' update technique within $resource

Hey there, I'm pretty new to Angular and looking for some guidance on how to implement a PUT update using angular $resource. I've been able to figure it out for all 'jobs' and one 'job', but I could use some assistance with in ...

The error message received was: "npm encountered an error with code ENOENT while trying to

About a week ago, I globally installed a local package using the command npm i -g path. Everything was working fine until today when I tried to use npm i -g path again and encountered the following error: npm ERR! code ENOENT npm ERR! syscall rename npm ER ...