【问题标题】:How to save the contents of a div as a image?如何将 div 的内容保存为图像?
【发布时间】:2013-09-06 01:04:01
【问题描述】:

基本上,我正在做标题所述的事情,试图将 div 的内容保存为图像。

我打算为 iPad 制作一个小型在线应用程序。

一个必须的功能是有一个“保存”按钮,可以将整个网页保存为图像,并将该图像保存到 iPad 的相机胶卷。我希望保存 div 的全部内容,而不仅仅是可见区域。

我在网上进行了简短的搜索,但找不到太多关于任何内容的文档。我在 HTML5 Canvas 上发现了很多东西。这是我整理的一些代码:

<script>
function saveimg()
{
    var c = document.getElementById('mycanvas');
    var t = c.getContext('2d');
    window.location.href = image;

    window.open('', document.getElementById('mycanvas').toDataURL());
}
</script>

<div id="mycanvas">
This is just a test<br />
12344<br />
</div>

<button onclick="saveimg()">Save</button>

虽然,我收到了这个错误:

TypeError: c.getContext is not a function

此应用程序将仅使用 HTML、CSS 和 jQuery(或其他 Javascript 库)构建。

【问题讨论】:

  • @GlenSwift - 谢谢你,但该帖子中的示例代码不起作用。
  • c.getContext 不是函数,因为 mycanvas 只是一个 div,而不是 canvas 元素。只有canvases 有上下文。

标签: javascript jquery html screenshot


【解决方案1】:

有几个相同的问题(12)。一种方法是使用画布。 Here's a working solutionHere 你可以看到一些使用这个库的工作示例。

【讨论】:

  • 每次使用时都会出现以下错误。 html2canvas(document.body).then(function(canvas) { document.body.appendChild(canvas); }); TypeError: undefined is not a function
  • 没有足够的信息来为您的问题提供正确的解决方案。什么函数未定义?错误何时何地抛出?我建议您为此创建新问题
  • 好吧,你给了他这个错误的信息,不要怪他说有错误,cmon man
【解决方案2】:

做这样的事情:

一个 ID 为 #imageDIV&lt;div&gt;,另一个 ID 为 #download&lt;div&gt; 隐藏的 ID 为 #previewImage

包括最新版本的jquery,以及来自the jspdf CDN的jspdf.debug.js

然后添加这个脚本:

var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
  html2canvas(element, {
    onrendered: function (canvas) {
      $("#previewImage").append(canvas);
      getCanvas = canvas;
    }
  });
});
$("#download").on('click', function () {
  var imgageData = getCanvas.toDataURL("image/png");
  // Now browser starts downloading it instead of just showing it
  var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
  $("#download").attr("download", "image.png").attr("href", newData);
});

点击#download 时,div 将保存为 PNG

【讨论】:

  • onrendered 永远不会执行,因此 getCanvas 未定义
  • onrendered 在 html2canvas 中显然已过时。改用 .then 方法,例如 `html2canvas(element).then(function(canvas){ yourcode(); });
猜你喜欢
  • 2013-07-26
  • 2011-11-12
  • 1970-01-01
  • 2010-12-12
  • 1970-01-01
  • 2019-10-22
  • 1970-01-01
  • 2012-09-25
相关资源
最近更新 更多