three.js toDataURL PNG is black

不打扰是莪最后的温柔 提交于 2020-01-23 17:40:06

问题


I'm trying to grab a screenshot with renderer.domElement.toDataURL("image/png"), and save it to a file. The image is the right size, but it's black. I have preserveDrawingBuffer turned on.

I think I'm decoding and saving the file correctly, because when I hexdump it I can see the correct initial characters for the PNG format, as well as the IHDR and IDAT chunk headers. However the closing IEND is missing.

Any known issues here? Hints? Windows 7/Firefox up to date if it matters.

Thanks... (Sorry if this is dumb, I'm very new to three.js)


回答1:


I had somewhat similar problems with Windows 7/Firefox. PNG Data URL's would be randomly truncated or something, much shorter than a successful PNG export. Trying to set that data url as image src resulted in "Image corrupt" exception or something in FF. As little sense it makse, setting a small window.setTimeout (10ms) between rendering and getting the data URL helped in my case. Maybe Firefox needs a rest from the JS engine before it refreshes some canvas internal state or something.. weird.




回答2:


I switched to JPG format (smaller files => truncation less of an issue?) and still saw it not working, then I tried this tip which I found here

If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:

 <?php
      $encodedData = str_replace(' ','+',$encodedData);
      $decodedData = base64_decode($encodedData);
 ?>

This worked. Thanks, Mekal.

This tip seems to apply to JPGs only. I saw PNGs decoding correctly without the + replacement, and corruptly with it. I can use JPGs so my personal problem is solved. However I never saw a PNG that wasn't black even when decoded correctly and not truncated.

Kind of a lousy situation either way, I feel like. What is up with the +'s?




回答3:


A black texture is a sign that you did not indicate the texture needs to be updated.

Also, you do not need to use canvas.toDataURL(). You can pass in the canvas reference to the THREE.Texture object.

var canvas = document.getElementById('#myCanvas');

var texture = new THREE.Texture(canvas);
texture.needsUpdate = true;

// Now render the scene


来源:https://stackoverflow.com/questions/16520818/three-js-todataurl-png-is-black

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