Marthy_Mc_Fly
Marthy_Mc_Fly

Reputation: 93

Is there a way to export a 3D model to a PNG image with Three.js

I want to make a webpage for a 3D vehicle model with Three.js where you can choose the perspective from where you can look at it. After you should be able to download a PNG image of this vehicle from that perspective with a transparent background.

The Three.js part is no problem. But downloading the image is an issue

Upvotes: 1

Views: 3550

Answers (2)

alwxkxk
alwxkxk

Reputation: 41

three.js is a library of webgl which draw in <canvas>.

<canvas> can sava as image whenever you want.

set three.js WebGLRenderer preserveDrawingBuffer as true:

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

save canvas as image:

<button id="save"> save image</button>
document.getElementById('save').onclick=()=>{
  saveImage()
}

function saveImage() {
  const canvas =  document.getElementsByTagName("canvas")[0]
  const image = canvas.toDataURL("image/png");
  const a = document.createElement("a");
  a.href = image.replace(/^data:image\/[^;]/, 'data:application/octet-stream');
  a.download="image.png"
  a.click();
}

codepen link :https://codepen.io/alwxkxk/pen/JjPMyNW

Upvotes: 2

SparkFountain
SparkFountain

Reputation: 2270

You can access the canvas element in which Three.js renders the 3D scene, and use it to create a download of its content. There is already a Stackoverflow post concerning this issue.

Upvotes: 0

Related Questions