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?

2 Answers2

8

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.

SpaceBison
  • 2,525
  • 1
  • 21
  • 38
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 :

Community
  • 1
  • 1
Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • 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.. – Santan Maddi Jan 18 '16 at 10:02
  • If you have access to the `renderer` variable, you can call `renderer.domElement.toDataURL()`, see my edit. – Kaiido Jan 18 '16 at 10:25
  • 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. – Santan Maddi Jan 19 '16 at 02:29
  • @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) – Kaiido Jan 19 '16 at 02:52