将屏幕截图裁剪为PhantomJS中的元素 [英] Crop screenshot to element in PhantomJS
问题描述
我知道可以使用page.clipRect()
在PhantomJS中任意裁剪屏幕截图:
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
};
因此,我正在尝试使用jQuery抓取特定元素的位置和宽度/高度.但是,我的代码如下(基于PhantomJS rasterize.js示例的最后一部分)无效;它只是保留默认值.
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);
}
});
推荐答案
在page.evaluate
内部运行的所有内容都无法从外部获得,执行被沙盒化,并受限于页面上下文.为了使它可用,请将其作为返回值,然后就可以访问它.
Anything you run inside page.evaluate
is not available from the outside world, the execution is sandboxed and confined with the page context. In order to have it available, make it as a return value and then you can access it.
看看包含的PhantomJS pizza.js
,其中的比萨店列表将返回给调用者.
Take a look at PhantomJS included pizza.js
where the list of the pizzeria is returned back the caller.
这篇关于将屏幕截图裁剪为PhantomJS中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!