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.
You can use rasterizeElement like this :
- 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
You can see the guidelines just by running the script with
the selector parameter,
, can be any valid CSS selector because under the hood this gets passed to
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...
Ping me on Twitter (@stephenhjames) if you have any suggestions or modifications to this script, or fork the gist on github and drop a comment
- 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
Labels: automate, phantomJS, png, raster, rasterize, script, SVG, vector