Skip to content

Instantly share code, notes, and snippets.

@Aeon
Forked from n1k0/gist:1501173
Last active August 29, 2015 14:05
Show Gist options
  • Save Aeon/bccf67fee339c590c8e7 to your computer and use it in GitHub Desktop.
Save Aeon/bccf67fee339c590c8e7 to your computer and use it in GitHub Desktop.
var page = new WebPage(),
address, selector, filename;
var system = require('system');
page.onConsoleMessage = function(msg) {
system.stderr.writeLine('console: ' + msg);
};
//capture and captureSelector functions adapted from CasperJS - https://github.com/n1k0/casperjs
capture = function(targetFile, clips) {
clips.forEach(function(clip, i) {
if (typeof clip != "object") {
// console.log(JSON.stringify(clip));
throw new Error("clip must be an Object instance");
}
var targetFilename = targetFile + '-' + i + '.png';
// console.log('Capturing page to ' + targetFile + ' with clipRect' + JSON.stringify(clip), "debug");
page.clipRect = clip;
try {
page.render(targetFilename);
} catch (e) {
console.log('Failed to capture screenshot as ' + targetFilename + ': ' + e, "error");
}
});
return this;
}
captureSelector = function(targetFile, selector) {
// var selector = selector;
var clips = page.evaluate(function(args) {
try {
var tables = document.querySelectorAll(args.selector);
return [].map.call(tables, function(el) {
var clipRect = el.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 });
console.log(JSON.stringify(clips));
return capture(targetFile, clips);
}
if (phantom.args.length < 2 || phantom.args.length > 5) {
console.log('Usage: render_selector.js URL SELECTOR FILENAME_PREFIX');
phantom.exit();
} else {
address = phantom.args[0];
selector = phantom.args[1];
filename = phantom.args[2];
page.onError = function (msg, trace) {
console.log("error on chart address: " + address);
console.log(msg);
trace.forEach(function(item) {
console.log(' ', item.file, ':', item.line);
});
}
// add a little extra space for scroll bars and such
page.viewportSize = { width: 1140, height: 1140 };
// page.paperSize = { width: 1140, height: 1140, border: '0px' }
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
} else {
window.setTimeout(function () {
captureSelector(filename, selector);
phantom.exit();
}, 200);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment