4

我正在尝试使用 html2canvas 在 JavaScript Angular 中创建一个“将 div 保存为 png”函数。它“几乎”有效,除了图像质量可能更好(主要是文本)

有时它只是打开一个空的画布,没有捕获里面的元素。

我没有使用下载功能,而是尝试只使用 window.open(data) ,但我仍然只是打开一个带有空画布的新窗口。我还确认在“另存为 png div”失败时收到了该 ID。

  $scope.savePNG = function(id) {
    var target = document.getElementById(id);

    html2canvas(target, {
      onrendered: function(canvas) {
        var data = canvas.toDataURL("image/png", 1);
        // data is the Base64-encoded image
        download(data, "Graph.png", "image/png");
        // window.open(data);
      }
    });
  };


  function download(data, filename, filetype) {
    // create an "off-screen" anchor tag
    var lnk = document.createElement('a');

    // the key here is to set the download attribute of the a tag
    lnk.download = filename;

    lnk.href = data;

    // create a "fake" click-event to trigger the download
    if (document.createEvent) {
      var e = document.createEvent("MouseEvents");
      e.initMouseEvent("click", true, true, window,
        0, 0, 0, 0, 0, false, false, false,
        false, 0, null);

      lnk.dispatchEvent(e);
    } else if (lnk.fireEvent) {
      lnk.fireEvent("onclick");
    }
  }
4

0 回答 0