Skip to content

Instantly share code, notes, and snippets.

@marcelduran
Created June 26, 2014 04:24
Show Gist options
  • Save marcelduran/2ce61b0b4b011ef9686d to your computer and use it in GitHub Desktop.
Save marcelduran/2ce61b0b4b011ef9686d to your computer and use it in GitHub Desktop.
Screenxote, screenshot of page regions
var args = require('system').args,
page = require('webpage').create();
// valid options
var opts = {
'v': 'viewport',
'a': 'area',
's': 'selector',
'o': 'output',
'c': 'custom'
};
// no args
if (args.length === 1) {
phantom.exit(1);
}
var url,
options = {};
for (var i = 1; i < args.length; i++) {
var o = args[i].replace(/^\-\-?/, '');
if (o in opts || (o[0] in opts && o === opts[o[0]])) {
options[opts[o[0]]] = args[i + 1];
i++;
} else if (!/^\-/.test(args[i])) {
url = args[i];
}
}
// no url
if (!url) {
phantom.exit(1);
}
// defaults
options.viewport = options.viewport || {width: 1280, height: 800};
options.output = options.output || 'page.png';
// ex:
// phantomjs screenxote.js http://twitter.com/marcelduran -s .profile-header-inner -o profile.png
// phantomjs screenxote.js http://twitter.com -a '{"top": "100", "left": "100", "width": "100", "height": "100"}'
// set values
page.viewportSize = options.viewport;
if (options.area) {
options.area = JSON.parse(options.area);
}
if (options.custom) {
page.customHeaders = JSON.parse(options.custom);
}
page.open(url, function (status) {
var rect = options.area;
function screenshot() {
console.log(JSON.stringify(rect, null, 2));
page.clipRect = rect;
page.render(options.output);
phantom.exit();
}
if (!rect) {
page.includeJs('//cdnjs.cloudflare.com/ajax/libs/zepto/1.0/zepto.min.js', function() {
//console.log(page.injectJs('zepto.min.js');
rect = page.evaluate(function(sel) {
var offset,
$el = $(sel);
if ($el.length === 0) {
return;
}
offset = $el.offset();
return {
top: offset.top,
left: offset.left,
width: $el.outerWidth(),
height: $el.outerHeight()
};
}, options.selector);
screenshot();
});
} else {
screenshot();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment