Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

javascript - How do you save an image from a Three.js canvas?

How do you save an image from a Three.js canvas?

I'm attempting to use Canvas2Image but it doesn't like to play with Threejs. Since the canvas isn't defined until it has a div to attach the canvas object to.

http://ajaxian.com/archives/canvas2image-save-out-your-canvas-data-to-images

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since the toDataURL is a method of canvas html element, that will work for 3d context too. But you have to take care of couple of things.

  1. Make sure when the 3D context is initialized you set preserveDrawingBuffer flag to true, like so:

    var context = canvas.getContext("experimental-webgl", {preserveDrawingBuffer: true});
    
  2. Then user canvas.toDataURL() to get the image

In threejs you would have to do the following when the renderer is instantiated:

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

Also, keep in mind this can have performance implications. (Read: https://github.com/mrdoob/three.js/pull/421#issuecomment-1792008)

This is only for webgl renderer, in case of threejs canvasRenderer though, you can simply do renderer.domElement.toDataURL(); directly, no initialization parameter needed.

My webgl experiment: http://jsfiddle.net/TxcTr/3/ press 'p' to screenshot.

Props to gaitat, I just followed the link in his comment to get to this answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...