Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
989 views
in Technique[技术] by (71.8m points)

jquery - Crop screenshot to element in 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 
            };

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...