Exporting a Three.js scene to a data URL is as easy

After attempting to save an image from a three.js WebGl render, I am encountering an issue where the saved image appears completely blank, despite returning a string of characters:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAK8AAADICAYAAACeY7GXAAADt0lEQ…IF4M2+znB4GcgWgDf7OsPhZSBbAN7s6wyHl4FsAXizrzP8AS/TAMmecuTCAAAAAElFTkSuQmCC

My code includes setting preserveDrawingBuffer to true:

 renderer = new THREE.WebGLRenderer( { 
    alpha: true,
    antialias: true,
    preserveDrawingBuffer: true
} );

Here is the section where toDataUrl is called:

var getImageData = false;
function render() {

            camera.lookAt( scene.position );

            renderer.render( scene, camera );
             if(getImageData == true){
                imgData = renderer.domElement.toDataURL("image/png");
                window.setTimeout(10);
                console.log(imgData);
                getImageData = false;
            }
            requestAnimationFrame(render);
        }


           getImageData = true;

Additionally, here is a snapshot of the canvas before being rendered to an image:

Canvas https://i.sstatic.net/b88NM.png

CanvasCode

<canvas width="175" height="200" style="width: 175px; height: 200px"></canvas>

If anyone has any insights or suggestions as to why the saved image turns out blank despite these settings, I would greatly appreciate the assistance. The render() function is located at the end of the code.

Answer №1

When working with WebGL, it's important to remember that it is an asynchronous API. This means that you will need to use either gl.finish() before calling toDataUrl() (although this can impact performance) or call it on the next frame. One way to achieve this is by utilizing setTimeout, but it must be done correctly like so:

if(getImageData == true) {
    window.setTimeout(function () {
        imgData = renderer.domElement.toDataURL("image/png");
        console.log(imgData);
    }, 100);
    getImageData = false;
}

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

Remembering previous scroll position with jScroll upon revisiting page

I'm implementing infinite scrolling of products on our site using jQuery jScroll. Can anyone guide me on how to save the scroll position when the user returns to the homepage? Appreciate any assistance! ...

Managing a large number of records in a for loop on a Node.js server can be challenging, especially when dealing with nearly

After setting up a NodeJS server and connecting it to a MySQL database with around 5000 users, I needed to read the data from MySQL and update a MongoDB database. I managed to write code for this process. https://gist.github.com/chanakaDe/aa9d6a511070c3c78 ...

When attempting to send data to the ServiceStack RESTful service, an error message of 'Access is denied' was received

I created a RESTful service using ServiceStack to send data to a database. It worked perfectly when tested locally. However, after deploying it to a server and running the same jQuery $.ajax call code, I encountered an 'Access is denied' error. I ...

endless cycle when utilizing useEffect with a mandatory function

I'm currently in the process of creating a custom hook for sorting and filtering tables within a dashboard application. However, I am encountering an issue with an infinite loop when attempting to refetch data after changing sort or filter fields. The ...

Activate jQuery function upon clicking a bootstrap tab

When I click on a Bootstrap tab, I want to trigger an AJAX function. Here is the HTML code: <li><a href="#upotrebljeni" data-toggle="tab">Upotrebljeni resursi</a></li> The jQuery AJAX function looks like this: $('a #upotreb ...

The networking feature stops functioning on Android devices after upgrading from Ionic 1.5.0 to 1.6.3

After upgrading from ionic 1.5.0 to 1.6.3 (the latest version), I noticed that networking ajax calls were no longer working on Android. I had to remove and re-add the android platform, and there seemed to be a change in the apk names from MainActivity-debu ...

Why does Vue continuously insert undefined values when adding non-consecutive indexes to an array?

In my application, users can select values from a dropdown list and add them to an array by clicking the "add" button. The goal is to use the selected value's id as the index in the array. For example: List of Values 1 - Apple 3 - Bananas 8 - P ...

Guide to encapsulating an angular material form within a component and making it accessible to the FormGroup as a formControl property

My goal is to create a custom component (let's call it custom-input) that acts as a formControl element using Angular material components. It should include the following structure: <mat-form-field > <input matInput [formControl]=" ...

Struggling to incorporate Three.js into a Vue project utilizing modules

Incorporating TrackballControl.js from the example folder of the npm package for Three.js into my Vue project using Webpack has been a challenge. After researching, I stumbled upon this helpful solution on Github. https://i.sstatic.net/KqSF6.png To imple ...

Dynamic binding in AngularJS with ng-repeat allows for seamless updating of data

I recently started using a helpful library called Angular Material File input <div layout layout-wrap flex="100" ng-repeat="val in UploadDocuments"> <div flex="100" flex-gt-sm="45"> <div class="md-default-theme" style="margin-le ...

Iterate through each row asynchronously, waiting for each one to complete before moving on to the

Trying to navigate through multiple pages using puppeteer has been successful, except when attempting to parse through them at the same time. The issue seems to stem from the code executing async operations in rapid succession, overwhelming the browser. My ...

Regularly updating a book's interactive pages with turn.js technology

I experimented with generating dynamic content in turn.js using the sample provided here. This is an excerpt of the code I have written: <body> <div id="paper"> </div> </body> <script type="text/javascript"> $(win ...

Navigating external pages with Vue Router

Could really use some assistance. I've got a JSON file filled with various URL links, some internal and some external. This is what the JSON structure looks like: [ {stuff..., "Url":"https://www.google.com/", stuff..}, {stuff... ...

Steps to retrieve hexadecimal addresses sequentially

Can anyone recommend a module or script that can generate sequential 64-bit hex addresses like the following: 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000001 00000000000 ...

KendoGrid encountered a JavaScript runtime error due to an invalid template

Having some trouble navigating the Kendo world and encountering an issue with a grid that is set to a JSON array data source. An error message stating "JavaScript runtime error: Invalid template" is displayed, specifically referencing null values in the d ...

Linking the location of the pop-up to the currently selected text box

I am currently experimenting with setting the top and left values relative to the selected_element (which is active at the time of triggering the popup) in a manner similar to a tooltip. I attempted to use $().position() in combination with jQuery, but it ...

Property usedJSHeapSize in Chrome

After doing some research online, I found that the documentation on this topic is quite lacking. I am currently dealing with a significant memory leak in my code and have been using: window.performance.memory.usedJSHeapSize However, it seems like the val ...

the method of utilizing JavaScript to showcase an HTML form

I have created a form for entering an employee's skills. Below the form, there is a link to add a new skill. When this link is clicked, the form should be displayed again. My code looks like this: <html> <head> ...

Stopping a build programmatically in Next.js involves implementing specific steps that aim to halt

Is there a method to programmatically halt the execution of npm run build in Next.js when a specific Error occurs within the getStaticProps function? Simply throwing an Error does not seem to stop the build process. ...

Create a loop to iterate through dates within a specified range using the Fetch API

When I need to get the exchange rate from the bank for a specific interval specified in the input, I follow these steps. The interval is defined as [startdate; enddate]. However, in order to make a successful request to the bank, the selected dates must be ...