Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Div to image with jQuery/JavaScript

I am trying to convert div to image using html2canvas library. I tried but no success can't convert full div to image, the dropper is missing in image.

URL: https://www.makethatvape.com/ejuicecalc/

Tried with code:

html2canvas($("#widget")).then(function(canvas) {
   bimg = canvas.toDataURL();  // by default png
});

So, any idea how to overcome this problem. I played with html2canvas and it work for text and CSS div to canvas conversion.

like image 728
user889030 Avatar asked Sep 22 '16 18:09

user889030


1 Answers

Try this

<div id="copyDiv"></div>

    var element = $("#widget"); // global variable
    var getCanvas; // global variable
    
    html2canvas(element, {
             onrendered: function (canvas) {
                    $("#copyDiv").append(canvas);
                    getCanvas = canvas;
                 }
      });

Note: If HTML markup contains an image tag, then for some browsers the above code will not be able to create the image of it. To make this work you need to use 2 parameters i.e. allowTaint, useCORS

Sample code :

html2canvas(document.getElementById("html-content-holder"), {
            allowTaint: true, useCORS: true
        }).then(function (canvas) {
            var anchorTag = document.createElement("a");
            document.body.appendChild(anchorTag);
            document.getElementById("previewImg").appendChild(canvas);
            anchorTag.download = "filename.jpg";
            anchorTag.href = canvas.toDataURL();
            anchorTag.target = '_blank';
            anchorTag.click();
        });

Detail Article: Convert HTML to image using jQuery / Javascript with live demos

like image 158
Satinder singh Avatar answered Oct 03 '22 03:10

Satinder singh