2

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);
    }
});
supertrue
  • 2,049
  • 5
  • 30
  • 49

1 Answers1

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.

Ariya Hidayat
  • 12,523
  • 3
  • 46
  • 39