Forked from n1k0/gist:1501173
Created
April 20, 2012 07:01
PhantomJS: Capturing single dom elements as png files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var page = new WebPage(), | |
address, output, size; | |
var retval = {}; | |
retval.result = "failed"; | |
retval.messages = []; | |
//capture and captureSelector functions adapted from CasperJS - https://github.com/n1k0/casperjs | |
capture = function(targetFile, clipRect) { | |
try { | |
page.render(targetFile); | |
} catch (e) { | |
return false; | |
} | |
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) { | |
} | |
}, { selector: selector })); | |
} | |
if (phantom.args.length < 2) { | |
//console.log('Usage: test2.js buttons.html .selector_class'); | |
retval.messages.push("2 arguments required."); | |
console.log(JSON.stringify(retval,undefined,4)); | |
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 | |
{ | |
console.log(phantom.args[1]); | |
//dump out each icon in buttons.html as individual png file | |
var outputfile = Math.round(Math.random() * 1000000) + ".png"; | |
if(captureSelector("/Users/rrrhys/projects/invites_ci/invitations/" + outputfile,phantom.args[1])){ | |
retval['result'] = "success"; | |
retval['filename'] = outputfile; | |
console.log(JSON.stringify(retval,undefined,4)); | |
} | |
else{ | |
} | |
phantom.exit(); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment