threejs canvas todataurl is blank

霸气de小男生 提交于 2020-01-11 09:27:12

问题


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?


回答1:


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.




回答2:


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 :

  • There is no preserveDrawingBuffer contextAttribute in the context2d API, only in the WebGL one.
  • You can create only one context per canvas element.
  • You can't set the preserveDrawingBuffer flag after context's creation
  • With three.js you can simply call renderer.domElement.toDataURL() (you'll need to go to the iframe target to be able to call from the dev tools).
  • Another solution, (and better than preserveDrawingBuffer flag) is to call canvas.toDataURL() in the rendering loop itself, before the browser takes controls again.


来源:https://stackoverflow.com/questions/34847293/threejs-canvas-todataurl-is-blank

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!