user889030
user889030

Reputation: 4754

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.

Upvotes: 6

Views: 33679

Answers (2)

Satinder singh
Satinder singh

Reputation: 10198

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

Upvotes: 8

Andrew
Andrew

Reputation: 20081

Simpler way to do it:

var convertMeToImg = $('#myDiv')[0];

html2canvas(convertMeToImg).then(function(canvas) {
    $('#resultsDiv').append(canvas);
});

https://html2canvas.hertzen.com/getting-started

Upvotes: 0

Related Questions