Created
December 20, 2011 10:33
-
-
Save fbuchinger/1501115 to your computer and use it in GitHub Desktop.
PhantomJS: Capturing single dom elements as png files
This file contains 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; | |
//capture and captureSelector functions adapted from CasperJS - https://github.com/n1k0/casperjs | |
capture = function(targetFile, clipRect) { | |
var previousClipRect; | |
if (clipRect) { | |
if (typeof(clipRect) !== "object") { | |
throw new Error("clipRect must be an Object instance."); | |
} | |
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('buttonfactory/icons/' + targetFile); | |
} catch (e) { | |
console.log('Failed to capture screenshot as ' + targetFile + ': ' + e, "error"); | |
} | |
if (previousClipRect) { | |
page.clipRect = previousClipRect; | |
} | |
return this; | |
} | |
evaluate = function(fn, context) { | |
context = (typeof(context) !== "object" ? context : {}); | |
var newFn = new functionInjector(fn).process(context); | |
return page.evaluate(newFn); | |
}, | |
/** | |
* Captures the page area containing the provided selector. | |
* | |
* @param String targetFile Target destination file path. | |
* @param String selector CSS3 selector | |
* @return Casper | |
*/ | |
captureSelector = function(targetFile, selector) { | |
page.currentSelector = selector; | |
var captureFunc = 'function(){return document.querySelector("'+selector+'").getBoundingClientRect()}'; | |
var cropBox = page.evaluate(captureFunc); | |
return capture(targetFile, {top: cropBox.top, left: cropBox.left, width: cropBox.width, height: cropBox.height}); | |
} | |
if (phantom.args.length != 1) { | |
console.log('Usage: maketheme.js theme.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 | |
{ | |
var iconRules = ['.ig-icon-alert','.ig-icon-arrow-1-n','.ig-icon-arrow-1-se','.long-gradient','.long-blue-gradient','.ig-icon-camera']; | |
for (var i = 0; i < iconRules.length; i++){ | |
var iconSel = iconRules[i]; | |
captureSelector(iconSel.slice(1)+'.png',iconSel); | |
} | |
phantom.exit(); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment