使用html2canvas获取<body>的屏幕截图并将img存储为JS var

mat*_*tyd 6 javascript screenshot image html2canvas

我试图让我的网站上的用户按下一个按钮来截取当前屏幕的截图(一切都在正文中).

根据我的研究,html2canvas似乎是一种可以实现这一目标的资源.

我的问题是文档没有提供示例代码,我正在努力控制所涉及的步骤.

http://html2canvas.hertzen.com/documentation.html

以下SO问题(如何使用html2canvas上传截图?)让我有点困惑.我只是想知道如何在这一点上获得一个图像.

从他的代码.

$(window).ready(function(){
    ('body').html2canvas();
    var canvasRecord = new html2canvas(document.body).canvas;

     //At this point does the .toDataURL method return a png?
});
Run Code Online (Sandbox Code Playgroud)

在这一点上,我迷失在图像的位置,甚至是如何/何时创建它.我担心以后会把它发送到服务器.

任何信息赞赏.谢谢!(甚至需要html2canvas?)

Liv*_*uel 4

当您使用 html2canvas jQuery 插件时,这里是一个示例片段

var screenshot;

$('body').html2canvas({
  onrendered: function(canvas) {
    screenshot = canvas.toDataURL();

    //code to process/send the image to server
  }
});
Run Code Online (Sandbox Code Playgroud)

在上面的代码片段中,html2canvas 创建页面的屏幕截图。

您还可以使用 PhantomJS 创建网页的屏幕截图 - 前提是它们是公共页面,因为您可能无法访问服务器端的登录保护页面;在这种情况下,只有像 html2canvas 这样的客户端解决方案才能工作。