简体   繁体   English

如何将iframe捕获为图像

[英]How to capture an iframe as an image

I have an iframe in my webpage where I can load websites dynamically. 我的网页中有一个iframe ,可以动态加载网站。 Is there any way to capture only the iframe and save it as an image? 有什么方法可以仅捕获iframe并将其另存为图像吗? If not possible, is it possible to take an screenshot of the whole page using JavaScript? 如果不可能,是否可以使用JavaScript截取整个页面的屏幕截图?

Web pages are not the best things to be "screenshoted", because of their nature; 由于网页的性质,它们并不是最好的“屏幕快照”; they can include async elements, frames or something like that, they are usually responsive etc... 它们可以包括异步元素,框架或类似的东西,它们通常是响应式的等等。

For your purpose the best way is to use external api or an external service, I think is not a good idea to try doing that with JS. 为了您的目的,最好的方法是使用外部api或外部服务,我认为尝试使用JS并不是一个好主意。

You should try url2png 你应该尝试url2png

Or use html canvas to do this 或者使用html canvas执行此操作

Look at the html2canvas project. 查看html2canvas项目。 Their approach is that they create a representation of the page inside a canvas. 他们的方法是在画布内创建页面的表示形式。 They don't make an actual screenshot, but builds it based on the content on the page and the loaded stylesheet. 他们没有制作实际的屏幕截图,而是根据页面上的内容和加载的样式表进行构建。 It could be used on the entire body or just a specific element. 它可以用于整个身体或仅用于特定元素。

It is also really easy to use. 它也真的很容易使用。 Here is an example: 这是一个例子:

 html2canvas(document.body, { onrendered: function(canvas) { document.body.appendChild(canvas); } }); 

You can adapt it to your code relatively easy. 您可以相对轻松地使其适应您的代码。

Take a look at their demo. 看看他们的演示。 Click on any of the buttons and then scroll to the bottom of the page. 单击任何按钮,然后滚动到页面底部。

To be able to use html2canvas in your iframe you may need to inject it in and then execute it from inside iframe context. 为了能够在iframe中使用html2canvas,您可能需要将其注入,然后从iframe上下文内部执行它。 The following may help you to achieve this: inject a javascript function into an Iframe 以下内容可以帮助您实现这一目标: 将JavaScript函数注入iframe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM