I know it's possible to arbitrarily crop a screenshot in PhantomJS, using page.clipRect()
:
page.clipRect = {
top: element_top,
left: element_left,
width: element_width,
height: element_height
};
So, I am trying to grab the positioning and width/height of a specific element using jQuery. However, my code below (based on the last section of the PhantomJS rasterize.js example) isn't working; it just keeps the default values.
I'm thinking I must have done something wrong with respect to variable scope. How can I get this to work?
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
} else {
var element_top = 0;
var element_left = 0;
var element_width = 200;
var element_height = 200;
page.evaluate(function() {
var $element = $('h1');
var offset = $element.offset();
element_top = offset.top;
element_left = offset.left;
element_width = $element.width();
element_height = $element.height();
});
window.setTimeout(function () {
page.clipRect = {
top: element_top,
left: element_left,
width: element_width,
height: element_height
};
page.render(output);
phantom.exit();
}, 200);
}
});
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…