Lab Sintesi
Lab Sintesi

Reputation: 71

How to export an image from a scene from threeJS

I'd like to export a 2d image of my scene by clicking a button on my html page. Which line of code should i add to my function? it does not seem to work and download the image. (I am using chrome as a browser)

const exportLink = document.getElementById( 'exportLink' );
exportLink.addEventListener( 'click', () => {

    rendererExport.render( scene, camera );
    const dataURL = rendererExport.domElement.toDataURL( 'image/png' );

    exportLink.href = dataURL;
    exportLink.download = 'export.png';

} );
}

here is my render function

function render() {

renderer.render(scene, camera);
  document.getElementById("colore").onclick= function(){
    somma= +slider.value + +slider1.value + +slider2.value + +slider3.value + +slider4.value;
    console.log(somma);

    if(somma<=70){
      customMaterial1.uniforms.glowColor.value.set( 0x668072 );
      customMaterial2.uniforms.glowColor.value.set( 0x4f6749 );
      customMaterial3.uniforms.glowColor.value.set( 0x491520 );
      customMaterial4.uniforms.glowColor.value.set( 0xb3c753 );
      customMaterial5.uniforms.glowColor.value.set( 0xe61f59 );
    }
}

Upvotes: 2

Views: 907

Answers (1)

TheJim01
TheJim01

Reputation: 8866

Your button is configured to execute the JavaScript function you shared. However, a download needs to perform a navigation action to trigger the download. The common way to do this is with a temporary anchor (<a>).

const exportLink = document.getElementById( 'exportLink' );
exportLink.addEventListener( 'click', () => {

    rendererExport.render( scene, camera );
    const dataURL = rendererExport.domElement.toDataURL( 'image/png' );

    let a = document.createElement( 'a' ); // Create a temporary anchor.
    a.href = dataURL;
    a.download = 'export.png';
    a.click(); // Perform the navigation action to trigger the download.

} );

Upvotes: 2

Related Questions