How to convert the HTML content into an image using jquery

Hi, In this tutorial, I am going to explain, How to convert the HTML content into an image using jquery.

If anybody wants to save / convert the HTML content as an image this code can be helpful.There is a jquery plugin i.e html2canvas, By using this plugin we can easily convert the HTML content of any part i.e a particular div content also to image.

This is like a snapshot of the HTML content, This functionality can be more useful when we have to generate the unique images dynamically.

First we need to include the jquery.min.js,html2canvas.js files to your project
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>  
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
This is my content here I am going to convert some image and text to image by using the html2canvas library
 <div class="col-md-offset-4 col-md-4 col--md-offset-4 top">  
   <div id="generateImg" style="border:1px solid;text-align:center;">  
    <img src="logo.png">  
    <h3>How to convert the html content into a image using jquery</h3>  
    <input type="text" value="" placeholder="Enter custom text here!!.." style="background-color: transparent;border: 0px solid;" class="form-control" width="300"/>  
    <br/>  
   </div>  
   <button id="gimg" type="button" class="btn btn-primary top pull-right">Generate Image</button>  
   <div id="img" style="display:none;">  
    <img src="" id="newimg" class="top"/>  
   </div>  
 </div>  
In the above code when we click on the generate image button then it will convert the entire first div content to image and it will display as an image in the second div.

Image generation code by using the html2canvas
  <script>  
   $(function(){  
   $("#gimg").click(function(){  
   html2canvas($("#generateImg"), {  
     onrendered: function(canvas) {  
     var imgsrc = canvas.toDataURL("image/png");  
     console.log(imgsrc);  
     $("#newimg").attr('src',imgsrc);  
     $("#img").show();  
   }  
   });  
   });  
   });  
 </script>  
 
Download Demo
* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff


EmoticonEmoticon