javascript 如何让 PhantomJS 在渲染截图时包含背景图片?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14336637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make PhantomJS include background images when rendering screenshot?
提问by mikel
I'm using PhantomJS to take screenshots of a webpage, with the page.render() method as detailed in https://github.com/ariya/phantomjs/wiki/Screen-Capture.
我正在使用 PhantomJS 截取网页的屏幕截图,使用https://github.com/ariya/phantomjs/wiki/Screen-Capture 中详述的 page.render() 方法。
It works fine except for background images, which allsomtimes appear blank. You can see an example of the problem if you go to http://screener.brachium-system.net/and enter http://www.bing.com/as the URL, there's a big empty space where the background image should be.
它工作正常,除了背景图像, 全部有时会出现空白。如果你去http://screener.brachium-system.net/并输入http://www.bing.com/作为 URL,你可以看到一个问题的例子,背景图像应该有一个很大的空白区域是。
Is there a way to force background images to be displayed ?
有没有办法强制显示背景图像?
回答by pawel
Worked fine for me using the default rasterize.js from Phantom examples:
使用Phantom 示例中的默认rasterize.js对我来说效果很好:
If the problem persists try to increase the delay between page load and rendering, it's set to 200ms (line 29 in the example code):
如果问题仍然存在,请尝试增加页面加载和呈现之间的延迟,将其设置为 200 毫秒(示例代码中的第 29 行):
page.open(address, function (status) {
/* irrelevant */
window.setTimeout(function () {
page.render(output);
phantom.exit();
}, 200);
}
To better understand why it should help: Phantom requests the page and renders it to an image as soon as it's fully loaded (all assets are in place and scripts executed). But the background image is loaded via JavaScript and the browser has no way to know in advance there are going to be more image requests. Setting longer delay between page load and taking the screenshot gives time to download and display images that may have been requested from a script.
为了更好地理解为什么它应该有帮助:Phantom 请求页面并在页面完全加载后将其呈现为图像(所有资产都已就位并执行脚本)。但是背景图片是通过 JavaScript 加载的,浏览器无法提前知道会有更多的图片请求。在页面加载和截取屏幕截图之间设置更长的延迟可以让时间下载和显示可能从脚本请求的图像。
回答by Alex Kl?ser
I came across a similar problem and found out that using webpage.onLoadFinished()worked in my case:
我遇到了类似的问题,并发现使用pages.onLoadFinished()在我的情况下有效:
// create a page instance
var page = require('webpage').create();
page.viewportSize = {
width: 800,
height: 600
};
// create some HTML code with an image in the background
style = 'background:url(file:///var/www/test.svg) no-repeat;';
style += 'background-size: contain;';
style += 'width: 100%; height: 100%;';
page.content = '<html><body style="' + style + '"></body></html>';
// onLoadFinished() will be called when the page finishes the loading
var outImage = '/var/www/test.png';
page.onLoadFinished = function() {
page.render(outImage);
phantom.exit();
};