Crop screenshot to element in PhantomJS

心已入冬 提交于 2019-12-18 05:20:46

问题


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);
    }
});

回答1:


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.

Take a look at PhantomJS included pizza.js where the list of the pizzeria is returned back the caller.



来源:https://stackoverflow.com/questions/11959139/crop-screenshot-to-element-in-phantomjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!