Created — forked from fbuchinger/gist:1501115

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

PhantomJS: Capturing single dom elements as png files

View gist:1501173
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
var page = new WebPage(),
address, output, size;
//capture and captureSelector functions adapted from CasperJS - https://github.com/n1k0/casperjs
capture = function(targetFile, clipRect) {
var previousClipRect;
var clipRect = {top: 0, left:0, width: 40, height: 40};
if (clipRect) {
if (!isType(clipRect, "object")) {
throw new Error("clipRect must be an Object instance.");
}
// previousClipRect = page.clipRect;
//page.clipRect = clipRect;
console.log('Capturing page to ' + targetFile + ' with clipRect' + JSON.stringify(clipRect), "debug");
} else {
console.log('Capturing page to ' + targetFile, "debug");
}
try {
page.render(targetFile);
} catch (e) {
console.log('Failed to capture screenshot as ' + targetFile + ': ' + e, "error");
}
if (previousClipRect) {
page.clipRect = previousClipRect;
}
return this;
}
 
captureSelector = function(targetFile, selector) {
var selector = selector;
return capture(targetFile, page.evaluate(function(selector) {
try {
var clipRect = document.querySelector(selector).getBoundingClientRect();
return {
top: clipRect.top,
left: clipRect.left,
width: clipRect.width,
height: clipRect.height
};
} catch (e) {
console.log("Unable to fetch bounds for element " + selector, "warning");
}
}, { selector: selector }));
}
 
if (phantom.args.length != 1) {
console.log('Usage: makebuttons.js buttons.html');
phantom.exit();
} else {
address = phantom.args[0];
page.viewportSize = { width: 200, height: 200 };
page.paperSize = { width: 1024, height: 768, border: '0px' }
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
} else
{
//dump out each icon in buttons.html as individual png file
var iconRules = ['.ui-icon-alert','.ui-icon-arrow-1-n','.ui-icon-arrow-1-se'];
for (var i = 0; i < iconRules.length; i++){
var iconSel = iconRules[i];
captureSelector(iconSel.slice(1)+'.png',iconSel);
}
phantom.exit();
}
});
}
nalbion commented

I'm trying to figure out how to do something like this as part of an automated acceptance test suite from a grunt task.

phantom.args has been removed from phantomjs 2.0 (http://phantomjs.org/api/phantom/property/args.html).

Add var system = require('system'); at the top of the file, then use system.args instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.