threejs canvas todataurl is blank
Asked Answered
A

2

5

Okay, I know that canvas.toDataUrl() will produce an image in png format. However, when I try to get the image from http://threejs.org/examples/#webgl_lines_sphere. All I see is a black image on chrome. To replicate the steps -

1) Open dev console and select the canvas element. 2) canvas = $0 3) context = canvas.getContext('webgl', {preserveDrawingBuffer: true}) 4) img = canvas.toDataUrl() 5) document.write('<img src="'+img+'"/>')

The image is blank. However, I tried with a different canvas at link http://threejs.org/examples/#canvas_geometry_cube. Please do the following steps to replicate.

1) Open dev console and select the canvas element. 2) canvas = $0 3) context = canvas.getContext('2d', {preserveDrawingBuffer: true}) 4) img = canvas.toDataUrl() 5) document.write('<img src="'+img+'"/>')

This gave the expected result. Why is there a difference and how can this be avoided to retrieve first image too?

Apterygial answered 18/1, 2016 at 4:21 Comment(0)
N
9

I was also getting a solid black image.

My code previously was:

this.renderer = new THREE.WebGLRenderer({premultipliedAlpha: false});

I have changed the parameter in the THREE.WebGLRenderer to:

this.renderer = new THREE.WebGLRenderer({preserveDrawingBuffer: true});

I am getting an image on taking a snapshot.

Hope it helps.

Nupercaine answered 10/7, 2018 at 7:17 Comment(0)
L
0

This is because the first example (see sources line 103) does use a THREE.WebGLRenderer creator, while the second one (see sources line 92) uses a THREE.CanvasRenderer.

Some notes :

Lacrimatory answered 18/1, 2016 at 9:2 Comment(4)
Is there a work around to capture the image after the entire document is rendered and not during the render loop? Assume that I cannot and would not be able to get my hands on the render loop..Apterygial
If you have access to the renderer variable, you can call renderer.domElement.toDataURL(), see my edit.Lacrimatory
It seems renderer.domElement.toDataURL() also does not work. Did it work for you, Kaiido? Also, there is no difference in accessing renderer.domElement and $0 in the console, as it just returns the canvas either way.Apterygial
@SantanMaddi, you're right, it doesn't work in Chrome... In Firefox however, if you do call twice the toDataURL or readPixel method, then you've got the image... I don't clearly get it... But if you don't have access to the rendering loop, I'll say that you're stuck, and the only way will be to perform a screenshot from outside the page (browser extension or OS app)Lacrimatory

© 2022 - 2024 — McMap. All rights reserved.