2013-02-01 11 views
19

PhantomJS为我捕获网页图像文件做得很好。我正在使用基于rasterize.js的脚本。PhantomJS截屏大小为内容

但是,对于某些固定大小的网页元素,我需要生成的图像以匹配网页元素的大小。

例如我有这样一个页面:

<html> 
<body> 
    <div id="wrapper" style="width:600px; height:400px;"> 
     Content goes here... 
    </div> 
</body> 
</html> 

在这个例子中,我需要它产生一个大小为600x400的图像。是否可以根据我正在栅格化的页面中的Web元素动态获取视口大小。

我知道这一个不是一个容易的想法?

谢谢

回答

23

哇。毕竟不是那么辛苦。只需将视口设置得非常大并使用cropRect函数即可。多么棒的工具!

MODS的rasterize.js:

page.open(address, function (status) { 
    if (status !== 'success') { 
     console.log('Unable to load the address!'); 
    } else { 
     var height = page.evaluate(function(){ 
      return document.getElementById('wrapper').offsetHeight; 
     }); 
     var width = page.evaluate(function(){ 
      return document.getElementById('wrapper').offsetWidth; 
     }); 
     console.log('Crop to: '+width+"x"+height); 

     page.clipRect = { top: 0, left: 0, width: width, height: height }; 
     window.setTimeout(function() { 
      page.render(output); 
      phantom.exit(); 
     }, 200); 
    } 
}); 
+2

给任何人在这里找到自己的方式对完美的PDF的追求 - clipRect是仅适用于图像现在(即使它没有明确地说,在文档)。有一个错误提交。 – Chords

+3

你为什么使用window.settimeout来渲染? – user20358

+2

如果页面显示带有动画等内容,则需要超时以确保所有元素都可见。 – Mika