[Solved-6 Solutions] Capture HTML Canvas as gif/jpg/png/pdf - javascript tutorial



Problem:

Check Whether it is possible to capture or print what's displayed in an html canvas as an image or pdf ?

Solution 1:

In this way we can use jsPDF to capture a canvas in an image or pdf.

var imgData = canvas.toDataURL('image/png');    
var doc = new jsPDF('p', 'mm'); 
doc.addImage(imgData, 'PNG', 10, 10); 
doc.save('sample-file.pdf'); 

Solution 2:

var canvas = document.getElementById("mycanvas");
var img    = canvas.toDataURL("image/png");

You can write it out as a new Image like this:

document.write('<img src="'+img+'"/>');

Solution 3:

HTML5 provides Canvas to Data URL(mimetype) which is implemented in Opera, Firefox, and Safari 4 beta. There are a number of security restrictions. So we don't need an additional library.

e.g.
 <canvas id=canvas width=200 height=200></canvas>
 <script>
      window.onload = function() {
          var canvas = document.getElementById("canvas");
          var context = canvas.getContext("2d");
          context.fillStyle = "green";
          context.fillRect(50, 50, 100, 100);
          // no argument defaults to image/png; image/jpeg, etc also work on some
          // implementations -- image/png is the only one that must be supported per spec.
          window.location = canvas.toDataURL("image/png");
      }
 </script>

Solution 4:

  • We can use "wkhtmltopdf".
  • wkhtmltopdf is open source (LGPLv3) command line tools to render HTML into PDF and various image formats using the Qt WebKit rendering engine.
  • These run entirely "headless" and do not require a display or display service.

Solution 5:

function exportCanvasAsPNG(id, fileName) {

    var canvasElement = document.getElementById(id);

    var MIME_TYPE = "image/png";

    var imgURL = canvasElement.toDataURL(MIME_TYPE);

    var dlLink = document.createElement('a');
    dlLink.download = fileName;
    dlLink.href = imgURL;
    dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':');

    document.body.appendChild(dlLink);
    dlLink.click();
    document.body.removeChild(dlLink);
}

Solution 6:

If we are using jQuery, we can use code like this:

var canvas = $("#mycanvas")[0];
var img = canvas.toDataURL("image/png");

$("#elememt-to-write-to").html('<img src="'+img+'"/>');




Related Searches to Capture HTML Canvas as gif/jpg/png/pdf ? - javascript tutorial