PyTux

Trips of a curious penguin.

Hello, time traveler! You are reading an article that is almost ten years old. The world has changed, and so have I and my opinions. There is a good chance what's below is not current, correct, or secure anymore, and maybe it never was. This page is preserved because I am an archivist at heart, but you have been warned.

Taking Retina screenshots with PhantomJS

With PhantomJS, a headless WebKit browser with Javascript API, you can automatically render a webpage like you see it on your screen in an image or PDF. This is an awesome feature, useful for testing or - that’s what I use it for - rendering some elements of the page as images for later use.

Here I will explain how to take Retina-like screenshots. These are screenshots with double width and height for the same element where the details are rendered with double the precision. There are different reasons to want that: you might not own a new iPad or an iPhone4* and want to see how your website would look on these devices or you might want to add a Retina unit test to your awesome test stack. I want to render text to images so that they will still look sharp on Retina screens when used as replacements.

The key is the CSS3 transform property and its scale(2) value, plus a couple of tweaks. Here is a modified version of the rasterize.js example to output Retina screenshots.

Bonus

You might want to render only a single element, for example your content div or your always-buggy sidebar, to an image.
Well, have a look at element.getBoundingClientRect (getBoundingClientRect is Awesome) and PhantomJS page.clipRect.

Here is a spoiler ;)

References