Learning Three.js

or WebGL for Dummies

Screenshot in Javascript

Sometime it would be cool if you could take a screenshot of your demo to share with your friends. This post will explain how to do that single a single line. Additionnaly, THREEx.screenshot helper is provided at the end if you want to add printscreen key in your demos without hasles.

Let’s get started

So as usual you got a renderer variable to render your 3D scene. This renderer contains a domElement property. It is a DOM element on which it renders, who would have guessed ? We will use the .toDataURL() method on this element to get the screenshot.

var dataUrl = renderer.domElement.toDataURL("image/png");

A single line and you are done! not too hard hey ? This line will return a url of the screenshot image in png format. This url is a data url, a special url which encode the content in base64. It looks like that data:image/png;base64,iVBORw0KGgo … Not too readable but quite usefull :)

Btw have you spotted he image/png parameter ? It is the mimetype of the image we will get. If you want a jpeg, just put image/jpeg instead.

WebGLRenderer special case

If your scene is renderered with WebGL, you should declare it like that.

var renderer   = new THREE.WebGLRenderer({
  preserveDrawingBuffer   : true   // required to support .toDataURL()

Notice the option preserveDrawingBuffer ? It is WebGLRenderer specific. This is required to support .toDataURL() as explained in the spec. Other renderers dont need it.

THREEx helper to make it even simpler

I wrote THREEx.screenshot, a THREEx helper to automatize the process and makes it as simple as possible. You download it from here and include it in your page like this

<script type="text/javascript" src="THREEx.screenshot.js"></script>

Would it be cool if got your own printscreen key for your 3D ? The following line will do exactly that. Everytime you press p, it does a screenshot of the renderer, and open a window containing it.


Note the aspect of the original image is preserved. The default callback behavior is to open a window containing the screenshot, so be carefull it may be stopped by popup blockers. It is possible to customize the default behaviors thru options. For more details, see the annoted source of THREEx.screenshot.