What is the process for changing the preserveDrawingBuffer setting in three.js?

Essentially, I am looking to set up a scenario where I can set preserveDrawingBuffer=true, render the scene once, capture the screenshot, and then revert back. However, this presents two challenges:

  • there is no function in the renderer to dispose of all buffers,
  • the canvas turns black if I attempt

    renderer = new THREE.WebGLRenderer({canvas:renderer.domElement,preserveDrawingBuffer:true});

Is there a proper way to achieve this?

UPDATE: Since I couldn't find a way to toggle this behavior, I ended up duplicating the scene and creating a second renderer to take the screenshot. Refer to https://github.com/mrdoob/three.js/issues/189

Answer №1

To capture a screenshot in JavaScript without using preserveDrawingBuffer: true, simply ensure that you take the screenshot immediately after rendering. As long as the screenshot is captured post-rendering but before exiting the current event, it will work reliably.

For instance, the following code snippet will consistently yield the desired result

renderer.render( scene, camera );
var screenshot = renderer.domElement.toDataURL();

In contrast, this approach may only produce random results due to its unpredictable timing

someElement.addEventListener('click', function() {
   // This is not executed immediately after rendering, making it unreliable.
   var screenshot = renderer.domElement.toDataURL();
});

In cases where users request screenshots in THREE.js examples, one can incorporate a render function for accurate captures like so

someElement.addEventListener('click', function() {
   render();
   var screenshot = renderer.domElement.toDataURL();
});

Alternatively, implement a solution such as the following:

var takeScreenshot;

function render() {
   ...
   if (takeScreenshot) {
     takeScreenshot = false;
     var screenshot = renderer.domElement.toDataURL();
   }
}

someElement.addEventListener('click', function() {
   takeScreenshot = true;
});

By ensuring that the screenshot is taken promptly after rendering, various methods can be employed to guarantee consistent and accurate results.

Answer №2

I recently faced a similar issue where my screenshot appeared blank in the three.js WebGL canvas because I forgot to set the renderer as follows: new THREE.WebGLRenderer({canvas:renderer.domElement,preserveDrawingBuffer:true}); To resolve this, here is my method for toggling preserveDrawingBuffer.

let canvas = this.renderer.domElement;
    canvas.getContext('webgl' , {preserveDrawingBuffer: true});
this.render();
var data = {
  image: canvas.toDataURL(),
};
canvas.getContext('webgl' , {preserveDrawingBuffer: 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

Dealing with unanticipated consequences in computed attributes - Vue.js

I am facing a challenge while working on the code below. I am attempting to utilize the getTranslation object to match values from the originalKeys array and then add these values to a new array called allKeys. However, ESLint has flagged an error stating ...

Frustratingly Quiet S3 Upload Failures in Live Environment

Having trouble debugging a NextJS API that is functioning in development (via localhost) but encountering silent failures in production. The two console.log statements below are not producing any output, leading me to suspect that the textToSpeech call ma ...

avoid inserting into a specific field with a specific name

I am trying to add a picture next to a specific name, but I am facing issues as there is no option for inserting it. This is how my table looks: https://i.sstatic.net/RRaTb.png How can I insert a picture in front of a particular name? The content of my ...

Learn the process of invoking an Angular scope function from within a JavaScript function located within a controller

In my Angular controller, I have a JavaScript function where I am trying to call an Angular function. However, I am encountering the error: $scope.Name is not a function, $scope.dates is not a function. function validation() { $scope.page ...

Is there a variance in window.innerWidth between Chrome and Firefox?

body, html { position:absolute; width:100%; height:100%; margin: 0; padding: 0; overflow: hidden; } When using window.innerWidth, there is a discrepancy between the values returned by Firefox and Chrome. Firefox return ...

Kendo's data-bind onclick feature functions properly on web browsers but fails to work on mobile devices

As a newcomer to Kendo and JavaScript, I may be missing something obvious... In one of my list entries, I have a simple call like this: <li style="margin: 0.5em 0 0.5em 0"> <a href="#transaction-details" data-bind="click: onB ...

Can Node.js be utilized to generate an XLS excel file while specifying the cell type?

I've noticed that many libraries have the capability to export to XLSX (Excel > 2007) or CSV formats, but not in XLS (which I assume is due to its outdated file format). I came across something where if you use fs.createOutputStream("filename. ...

Points in an array being interpolated

I am currently working with data points that define the boundaries of a constellation. let boundaries = [ { ra: 344.46530375, dec: 35.1682358 }, { ra: 344.34285125, dec: 53.1680298 }, { ra: 351.45289375, ...

Transform Ajax response into dropdown menu option

I have made an ajax call and received HTML as a response. Now, I need to convert this output into options and add them to select tags on my webpage. <div class="views-element-container"> <div class="view view-contact-view-id-conta ...

Is there a way for me to generate a preview thumbnail for my video?

Looking to add a preview effect to video thumbnails when users hover over them, displaying a series of frames from the video. Are there any jQuery plugins or tutorials available for creating this effect? ...

Explore numerous databases using mongoosastic

Currently in my Node.js application, I am utilizing Mongoosastic to fetch data from ElasticSearch : Article.search({ "match_all": {} }, function (err, results) { console.log(results.hits.hits); Post.search({ "match_all": {} }, function (err, r ...

In TypeScript, the catch block does not get triggered

I created a custom pipe in Angular that is supposed to format passed parameters to date format. The pipe contains a try-catch block to handle any errors, but surprisingly the catch block never seems to be executed even when an invalid date is passed. impo ...

What is the best way for Protractor to effectively wait for a popover to be displayed and verify that it does not contain an empty string?

Whenever you hover over it, this appears - my popup: https://i.sstatic.net/Bm9tC.gif This is what the html looks like before we add the popover to the DOM: <span tariff-popover="popover.car2go.airport" class="ng-isolate-scope"> <s ...

Converting XML to JSON in a Node.js application

I recently read an article on that explained the conversion process clearly, but unfortunately it's not working for me. Let me provide you with the code snippet: function parseXml(xml) { var dom = null; if (window.DOMParser) { try ...

Exploring the Strategy of Incorporating Dynamic Keys into TypeScript for Easy Referencing

I am facing a scenario where I receive keys from the backend and need to design an interface based on these keys. By creating a dynamic interface, I can easily bind these properties. const KEYS_FROM_API = ['ARE_YOU_SURE', 'NOT_NOW', &ap ...

My goal is to generate four HTML buttons that trigger specific functions: addition, subtraction, multiplication, and division

I am currently learning JavaScript, and I am facing some challenges with my assignment. The task is to create four buttons in HTML that trigger different functions - addition, subtraction, multiplication, and division. The goal is for the user to input two ...

A guide to JavaScript: Fetching and Parsing JSON Data from an API

Hey there! I've been working on using this code snippet in my defult.js file to call an API, but I'm having trouble figuring out how to read the output. It always seems to end up in the last else part. function fetchDataDist(APPID, flag, call ...

Having trouble with installing create-react-app for my_app using npm because it seems to be stuck on f

I've hit a roadblock while trying to create a react app on my 2011 MacBook Pro. To start, I downloaded the latest version of Node from their official website. Following the instructions from React documentation, I ran the following commands: npm uni ...

What is the best way to remove current markers on google maps?

This is how I implemented it in my project. The issue I'm facing is that the clearAirports function does not seem to clear any existing markers on the map or show any errors in the Google console. googleMaps: { map: null, init: function () { ...

"Encountering a 404 error when submitting a contact form in Angular JS

Looking to set up a contact form for sending emails with messages. Currently diving into Angular Express Node Check out the controller code below: 'use strict'; /** * @ngdoc function * @name exampleApp.controller:ContactUsCtrl * @descripti ...