使用(?)语言将元素的内容绘制到Canvas元素/捕获网站上作为图像

时间:2011-05-18 19:31:34

标签: image canvas render

我问了一个关于从HTML编译图像文件的问题。 MichaëlWitrant回复并告诉我关于canvas元素和html5。

我在网上看了SO,但是我没有发现任何关于在画布上绘制misc元素的内容。这可能吗?

例如,假设我有一个带背景图像的div。有没有办法让这个元素和它的背景图像“放到”画布上?我问,因为我找到了一个允许将canvas元素保存为PNG的脚本,但我真正想做的是将DOM元素的集合保存为图像。

修改

哪种语言无关紧要,如果可行,我愿意尝试。

3 个答案:

答案 0 :(得分:1)

对于记录,drawWindow仅适用于Firefox。

此代码仅在本地而非互联网上使用,使用带外部元素的drawWindow会产生安全性异常。

在我们回答任何其他问题之前,您必须向我们提供更多背景信息。

答案 1 :(得分:0)

http://cutycapt.sourceforge.net/

CutyCapt是一个命令行实用程序,它使用Webkit将HTML呈现为PNG,PDF,SVG等。您需要以某种方式与它进行交互(例如PHP中的shell_exec),但它非常强大。站点的渲染方式与Webkit浏览器中的完全相同。

我没有特别使用过CutyCapt,但强烈推荐给我。我使用了一种名为WkHtmlToPdf的类似产品,这在我的个人经历中非常棒。

答案 2 :(得分:0)

经过多次尝试使用drawWindow参数,即绘制错误的部分或元素后,我设法通过两步处理来完成:首先在画布中捕获整个页面,然后在另一个画布中绘制该画布的一部分。

这是在XUL扩展中完成的。 drawWindow在其他浏览器中不起作用,并且由于安全原因可能无法在非特权上下文中工作。

function nodeScreenshot(aSaveLocation, aFileName, aDocument, aCSSSelector) {
  var doc = aDocument;
  var win = doc.defaultView;
  var body = doc.body;
  var html = doc.documentElement;

  var selection = aCSSSelector
    ? Array.prototype.slice.call(doc.querySelectorAll(aCSSSelector))
    : [];

  var coords = {
    top: 0,
    left: 0,
    width: Math.max(body.scrollWidth, body.offsetWidth, 
                      html.clientWidth, html.scrollWidth, html.offsetWidth),
    height: Math.max(body.scrollHeight, body.offsetHeight, 
                       html.clientHeight, html.scrollHeight, html.offsetHeight)

  var canvas = document.createElement("canvas");

  canvas.width = coords.width;
  canvas.height = coords.height;

  var context = canvas.getContext("2d");
  // Draw the whole page
  // coords.top and left are 0 here, I tried to pass the result of
  // getBoundingClientRect() here but drawWindow was drawing another part,
  // maybe because of a margin/padding/position ? Didn't solve it.
  context.drawWindow(win, coords.top, coords.left,
                     coords.width, coords.height, 'rgb(255,255,255)');

  if (selection.length) {
    var nodeCoords = selection[0].getBoundingClientRect();
    var tempCanvas = document.createElement("canvas");
    var tempContext = tempCanvas.getContext("2d");

    tempCanvas.width = nodeCoords.width;
    tempCanvas.height = nodeCoords.height;
    // Draw the node part from the whole page canvas into another canvas
    // void ctx.drawImage(image, sx, sy, sLargeur, sHauteur,
                                 dx, dy, dLargeur, dHauteur)
    tempContext.drawImage(canvas,
      nodeCoords.left, nodeCoords.top, nodeCoords.width, nodeCoords.height,
      0, 0, nodeCoords.width, nodeCoords.height);

    canvas = tempCanvas;
    context = tempContext;
  }

  var dataURL = canvas.toDataURL('image/jpeg', 0.95);
  return dataURL;
}
相关问题