Convert any Html element to Image using canvas in Angular

 

In this post we going to take about how to convert html element to image. For that I am going to using angular module html2canvas.

This library is working fine with below mentioned browsers:-

  • Google Chrome
  • Microsoft Edge
  • Opera 12+
  • Firefox 3.5+
  • Safari 6+
  • IE9+

Installation

Install the library in the application using NPM or if you prefer Bower.

          npm install html2canvas
                // or
         bower install html2canvas

 For JavaScript application 

         <script src="/path/to/html2canvas.min.js"></script>


Creating Screenshot using Html2Canvas

Now time for capture the screenshot of html page in your web application. 

    let element = document.querySelector("#div");
        html2canvas(document).then(function(canvas) {
    
            // Converting in image 
            canvas.toBlob(function(blob){
                // To download directly on browser default 'downloads' location
                let link = document.createElement("a");
                link.download = "screeshot.jpeg";
                link.href = URL.createObjectURL(blob);
                link.click();
    
            },'image/jpeg');
        });

This is code simply create a jpeg file of your div which you're in div query selector.

Once the blob is convert into image you  need to create a tag which are going to use for download the image. The file is directly download in default download location.

But if you want user save manually that image for that you need to add window.saveAs() function. Using this function user are able to get popup for chosing location and all.


Hope you like the post☺.




Post a Comment

1 Comments