Tips for preventing annoying screen flickering and refreshing when loading JSON data using p5.js

My current project involves using p5.js to render a 3D cube on a webpage, and I need to continuously update color information from JSON files. These JSON files are updated every second as a python script runs in the background.

The issue I'm facing is that my webpage keeps refreshing and flickering, disrupting the smooth rendering of visual features from the JSON data. How can I modify my code to ensure that the colors are smoothly rendered without any interruptions? Any advice or suggestions would be greatly appreciated.

Below is the p5.js code I am currently working with:

var color_data
var urls = "http://127.0.0.1:5500/data.json";
let fr = 500

function setup() {
    createCanvas(windowWidth, windowHeight, WEBGL);
    setInterval(loadData, 100)
    frameRate(fr);
    easycam = createEasyCam();
    document.oncontextmenu = () => false;
    easycam.setDistance(800, 0);
}

function gotData(data) {
    color_data = data
}

function loadData() {
    loadJSON(urls, gotData)
}

function windowResized() {
    resizeCanvas(windowWidth, windowHeight)
}

function draw() {

    function colorPart(x_value, y_value, z_value) {
        let arr = color_data[5 - y_value][5 - z_value][x_value]
        return arr.split(',')
    }

    function forRange(fn) {
        const cubeSpacing = 100
        for (let i = -250; i <= 250; i += cubeSpacing) {
            fn(i);
        }
    }

    function coordToIndex(num) {
        return (num / 50 + 5) / 2
    }

    background(155);

    translate(0, 0, -500);

    rotateY(millis() / 2000);

    // let size = Math.random() % 10 *25
    // let volume = Math.random() % 1 + 1
    let volume = 1

    forRange(x => forRange(y => forRange(z => {
        let pos = createVector(x, y, z);
        noStroke()
        push();
        translate(volume * pos.x, volume * pos.y, volume * pos.z);
        let index_x = coordToIndex(x)
        let index_y = coordToIndex(y)
        let index_z = coordToIndex(z)
        if (color_data) {
            let tem_arr = colorPart(index_x, index_y, index_z)
            fill(parseInt(tem_arr[0]), parseInt(tem_arr[1]), parseInt(tem_arr[2]));
        }
        sphere(18)
        pop();
    })))

}

Answer №1

What I wanted to show in my previous comment is exemplified here.

I made a change by moving most of the calculations outside of the draw function. In the setup function, we populate the spheres array with positions and an initial color. Then, the setInterval(changeColor, 500) function updates the colors randomly. This can be modified to work with data from a JSON file as well.

    colors = ["red", "blue", "green", "cyan", "white", "black", "yellow"]

    function setup() {
        spheres = []
        forRange(x => forRange(y => forRange(z => {
            color = "red"
            spheres.push({ x, y, z, color })
        })))

        createCanvas(windowWidth, windowHeight, WEBGL);
        frameRate(500);
        document.oncontextmenu = () => false;
        setInterval(changeColor, 500)
    }

    function changeColor() {
        spheres.forEach(obj => {
            obj.color = colors[int(random(colors.length))]
        })
    }

    function forRange(fn) {
        const cubeSpacing = 120
        for (let i = -250; i <= 250; i += cubeSpacing) {
            fn(i);
        }
    }

    function draw() {
        background(155);
        translate(0, 0, -500);
        rotateY(millis() / 2000);
        rotateX(millis() / 8000);

        spheres.forEach(obj => {
            noStroke()
            push();
            translate(obj.x, obj.y, obj.z);
            fill(obj.color)
            sphere(18)
            pop();
        })
    }

See it in action here: with smooth transitions (at least on google chrome, tested there only)

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

The issue with CORS is preventing the AJAX POST request from reaching the Express.js server, even with body-parser configured

Recently, I have been trying to send an AJAX POST request from my HTML page that is hosted on an Apache server. The goal of this request is to post a filename to an express.js server in order to perform some operations with another node. To facilitate this ...

Ways to pause JavaScript execution until a function completes its task

Is it possible to pause JavaScript execution until a specific function finishes in JavaScript/NodeJS? For instance: https://i.stack.imgur.com/Ta8pj.png Imagine the first line of code triggers an alert, and JavaScript stops executing until the user interac ...

Verify whether two images are identical

I need to find a way to determine if the image selected randomly using math.random matches the image chosen by the user with style="solid 3px #587388". If the two images match, I want to display an alert saying "Won", otherwise "lose". How can I achieve th ...

The UIManager could not find the required native component in requireNativeComponent

I understand that this question has been raised multiple times, but previous inquiries have focused on integrating a third-party dependency in a react-native app. In my case, the issue stems from my own native code, and I am struggling to resolve it. My cu ...

Error encountered in Three JS Drag Controls: Unable to assign value to property 'x' as it is undefined

I've been trying to drag the spheres around the scene using drag controls that should be activated when the "m" key is pressed. However, I keep running into an issue where the objects don't move and I receive an error message saying "Uncaught Typ ...

When using Python's pyshark library with the parameter use_json=True, it encounters issues with

I am currently using the pyshark library to extract JSON data. Below is the code snippet I'm utilizing: import pyshark import json capture = pyshark.LiveCapture(interface='eth0', bpf_filter='http', use_json=True) for packet in c ...

Why is my Node.js callback firing twice?

Can you explain why the createFile callback is firing twice in the code below? This issue only occurs when the server is processing multiple requests simultaneously, not with a single request. The client making the request is not a browser; it's anoth ...

Flickering transitions in Phonegap and jQuery Mobile pages

As a beginner in Phonegap/jQuery Mobile, I have encountered a frustrating issue of a white screen appearing during page transitions. Despite trying various solutions found online, such as using -webkit-backface-visibility:hidden;, the problem persists. I ...

Is it possible to set environment variables in Next.js outside of the pages directory?

Are there alternative methods for setting environment variables outside of a pages directory in NextJS? I have a utility function that defines the base API route in one centralized location. However, since this is a utility function and not associated with ...

How can I connect HTML and JavaScript to get the clicker functioning?

While the HTML and javascript work flawlessly on jsfiddle where I initially created this project, I'm encountering a problem with Google Drive's hosting. The HTML displays correctly but there is no interaction happening with the javascript. Belo ...

Progress bar for multiple file uploads using AWS JavaScript SDK

I have successfully uploaded my files to s3, but now I want to track the progress of each file being loaded. bucket.upload(params, function(err, data){ console.log("File Uploaded Successfully"); }).on('httpUploadProgress', function(progress){ ...

Tips for uploading a file with AngularJS using the multipart/form-data format

Looking for guidance on uploading an image using AngularJS with a REST API that requires Content-Type:multipart/form-data. Content-Type:multipart/form-data www.abc.com/images/id Request Body { // --Boundary_1_1626119499_1392398808202 // Conten ...

JSON parsing throws an error due to encountering an 'unexpected end of input' issue

Here's some code I'm working with: var default_links = '{ "name" : "Google", "url": "https://encrypted.google.com/", "fav_url": "https://encrypted.google.com/favicon.ico" }\n'+ '{ "name" : "Yahoo", "url": "http://www. ...

Experiencing issues when attempting to post JSON data (using node request) to an Express server in order to store it in

Utilizing MongoDB as the backend database for my node/Express application has presented a challenge. Specifically, configuring the body-parser in my Express app to receive the full JSON data posted by the client app (also a node.js application) is proving ...

The optimal method for computing the Fibonacci sequence using JavaScript

Improving my skills in optimizing algorithms and understanding big-o notation is a priority for me. I devised the following function to compute the n-th Fibonacci number. It works well for higher inputs, but I wonder how I can enhance it. What are the dow ...

Enrolling in the system and working with Java servlets

Registration forms on my website trigger a Java Servlet to check the database for existing usernames or emails. How can I ensure the client receives a response from the Servlet indicating whether the registration was successful or not? The desired outcome ...

How to retrieve the value of a nested checkbox in Angular using dynamic methods

I successfully developed dynamic nested checkboxes in Angular and now I am looking to retrieve the values of the selected checkboxes. However, I encountered an issue with the JSON structure needed to implement this functionality. https://i.stack.imgur.com ...

steps for transferring a shallow copy of an array to a function

How can I adjust this code so that when I press each button, the console.log displays a different slice of the array instead of always showing me the last 20 elements? for (var i = 0; i < array.length; i++) { var b; var NewArr = []; ...

Retrieve GET ajax requests from a webpage by simply entering the URL

Here's an example from the API I'm currently working with: This particular page relies heavily on GET calls to load most of the data. Three main calls that catch my interest are: All these calls share a common feature, which is the numeric ID ...

How can I effectively capture a change in the hour using Node.js?

Do you know of a more efficient way to monitor datetime changes instead of checking every 10 minutes, potentially firing nearly 10 minutes late? Any alternative solutions that I may have overlooked for this issue? ...