Convert 3d model in threejs scene to png image

Hi everyone,
I’m trying to convert an uploaded stl file into an image with png extension. I have written a code that only captures the scence, but the image is not showing. I don’t know why the image is not displayed.
Here is a piece of the codes:

var canvas = document.getElementsByTagName('canvas')[0];
  var dataURL = canvas.toDataURL('image/png');
  var imgSrc = dataURL.replace(/^data:image\/[^;]/, 'data:application/octet-stream');
  console.log({dataURL});
  var image = imgSrc;

The code above only captures the scene without showing the image.
If I use imgSrc.png, it gives me error.

Can anyone help me with this please.

Does this answer your question?

Thanks for replying.
Unfortunately, I’m still getting the same result.

Thanks man.

I’ve just fixed it. I think because I forgot to render the scene camera that’s why it didn’t work at first.

1 Like

Is it possible to get only the content (the image) in the scene without the scence background appearing?

To remove the background for rendering the image, change the scene.background color to an rgba value 0,0,0,0 before renderer.render(scene camera);
Make sure you set canvas to transparent to start with though:

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

After saving the blob, change the scene.background = ; back to your original setting and call renderer.render(scene, camera); to update.

Unless you don’t want the background after the image is loaded, then don’t call the second scene.background = ;

Thanks, Timmy. This is helpful, I will try it out straightaway