-
Notifications
You must be signed in to change notification settings - Fork 23
Screen Capture
Since PhantomJS is using WebKit, a real layout and rendering engine, it can capture a web page as a screenshot. Because PhantomJS can render anything on the web page, it can be used to convert contents not only in HTML and CSS, but also SVG and Canvas.
The following script demonstrates the simplest use of page capture. It loads the Github homepage and then saves it as an image, github.png
.
var page = require('webpage').create();
page.open('http://github.com/', function () {
page.render('github.png');
phantom.exit();
});
To run this example create a new file called 'github.js' which is in the same directory as the phantomjs.exe file. Copy and paste the above code into the github.js file. Now at the command line, in the same directory as the phantomjs.exe and the new github.js file run the code below:
phantomjs github.js
Beside PNG format, PhantomJS supports JPEG, GIF, and PDF.
In the examples
subdirectory, there is a script rasterize.js (30 lines) which demonstrates a more complete rendering feature of PhantomJS. An example to produce the rendering of the famous Tiger (from SVG):
phantomjs rasterize.js http://ariya.github.com/svg/tiger.svg tiger.png
which gives the following tiger.png
:
Another example is to show polar clock (from RaphaelJS):
phantomjs rasterize.js http://raphaeljs.com/polar-clock.html clock.png
Producing PDF output is also easy, e.g. from a Wikipedia article:
phantomjs rasterize.js 'http://en.wikipedia.org/w/index.php?title=Jakarta&printable=yes' jakarta.pdf
Canvas can be easily constructed and converted to an image. The included example colorwheel.js (50 lines) produces the following color wheel:
It is possible to build a web screenshot service using PhantomJS. There are some projects which make it easy to create such a service. Examples of PhantomJS-based screenshot services are Screener and ChromaNope.