PhantomJS is a headless Webkit browser. In other words, it's all the awesome of Safari/Chrome without the UI and is capable of injecting Javascript into a loaded page, evaluating expressions within the browser sandbox and
screen capture.
Its that last little bit that I'm really interested in, screen capture, so I headed along and found this simple
rasterize.js script (provided by the creator of PhantomJS) which is good for taking full screenshots of your web-browser, but not so good if you are wanting to only take a screenshot of a particular element.
So I wrote a script called
rasterizeElement.js which takes advantage of the webpage object's clipRect property and sets the clipping rectangle according to the boundaries of the element you are selecting.
Loading ....
You can use rasterizeElement like this :
Getting Started
- Download and install PhantomJS (if you haven't already)
- Download rasterizeElement.js and save it in the same folder as PhantomJS
- Run the script according to the Usage Guidelines below
Usage Guidelines
You can see the guidelines just by running the script with
phantomjs rasterizeElement.js
the selector parameter,
renderElementBySelector
, can be any valid CSS selector because under the hood this gets passed to
document.querySelector()
method to get a reference to the element in the DOM.
Bits and Bobs Under the Hood
If you are going to modify or want to work with the rasterizeElement script, here are some things that are worth a mention...
- I was unable to get an realistic clipping rectangle for the selected element until I used the page.evaluate function. This was due to my PhantomJS ignorance, it makes sense that evaluation of the webpage happens in this controlled sandbox.
- If you want to use the optional arguments viewPortsize and paperSize, you will have to escape your object literals in the command line.
- Refer to the original file rasterize.js to see acceptable papersizes if you are wanting non A4 pdf
Ping me on Twitter (@stephenhjames) if you have any suggestions or modifications to this script, or fork the gist on github and drop a commentLabels: automate, phantomJS, png, raster, rasterize, script, SVG, vector