4

I'm trying to create a 'save div as png' function in JavaScript angular with html2canvas. It 'almost' works, except for the image quality could be better (mostly text)

BUT sometimes it just opens an empty canvas not capturing the elements inside.

Instead of using the download function i tried to just window.open(data) and i still just opens a new window with an empty canvas. i also confirmed that the id is received on failing 'save as png divs'.

  $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");
    }
  }
Lulylulu
  • 1,254
  • 8
  • 17
Anders Pedersen
  • 2,255
  • 4
  • 25
  • 49

0 Answers0