Search code examples
javascriptjqueryhtmlcsshtml2canvas

How to generate a html2canvas images with a hidden source (html) div


I am working in a project where I need to generate a profile picture of any member and its reviews, and some data, I started working with GDI, but it was so hard to understand, so I searched for other options and found Html2Canvas that works with javascript/jquery, everything is fine, the only thing I couldn't handle, and would like to know if there is a way to hide the source html div without breaking the result image.

Ex:

This is how is it now

Original code

This is how it should look

How It should be

So, when I apply display:none on the css of the source div, the image result is like this:

Broken Image

And finally here is the code that I have so far

var div_to_hide = $("#mydiv:hidden");
$(function() {
    $('span.stars').stars();
});
html2canvas([document.getElementById('mydiv')], {
    onrendered: function (canvas) {
        document.getElementById('canvas').appendChild(canvas);
        var data = canvas.toDataURL('image/png');
        var image = new Image();
        image.src = data;
        document.getElementById('image').appendChild(image);
    }
});
$.fn.stars = function() {
    return $(this).each(function() {
        var val = parseFloat($(this).html());
        val = Math.round(val * 4) / 4;
        var size = Math.max(0, (Math.min(5, val))) * 16;
        var $span = $('<span />').width(size);
        $(this).html($span);
    });
}

https://jsfiddle.net/ricardojriosr/6ap9Lx1f/8/

Now the question is how do I made this work showing only the image and not the HTML source. Thanks in advace.


Solution

  • Instead of trying to hide it before, hide (or remove) it after the canvas is rendered.

    I'm not sure why var div_to_hide equals $("#mydiv:hidden"); but if you change it to var div_to_hide = $("#mydiv"); then, on line 12, after appending the image, you can run div_to_hide.hide();

    And to avoid a flash of the HTML content, you can use some CSS trickery to cover up the original HTML. I made an example here, but you can adjust to fit whatever your actual needs are. https://jsfiddle.net/m5zq2kzn/