title: Crop screenshot to element in PhantomJS
body: <p>I know it's possible to arbitrarily crop a screenshot in PhantomJS, using <code>page.clipRect()</code>:</p>
  
  <pre><code>            page.clipRect = { 
                  top: element_top, 
                  left: element_left, 
                  width: element_width, 
                  height: element_height 
              };
  </code></pre>
  
  <p>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 <a href="http://code.google.com/p/phantomjs/wiki/QuickStart" rel="nofollow">rasterize.js example</a>) isn't working; it just keeps the default values. </p>
  
  <p>I'm thinking I must have done something wrong with respect to variable scope. How can I get this to work?</p>
  
  <pre><code>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);
      }
  });
  </code></pre>