Search code examples
javascriptjqueryhtml2canvas

Issues with deferring function


I have a function that basically makes a new div from existing divs and then generates an image from that. This all works fine. After this is complete, I'd like to empty and hide this new div. I thought I could use some deferred function to ensure that the new div doesn't empty before the function that makes the image is complete. If they happen at the same time or the empty happens first, then the image generated is blank (since the div is empty).

In my code, the function to empty and hide the new div is happening at the same time or before the function to make the image. How can I ensure that the function to empty and hide the new div comes after the function to create the image is entirely complete.

My code looks like this:

$('#export_all').click(function(){
    $('#gen_narr').hide();
    $("#full_complete").empty();

    var storyboard = $(this).closest('div').find(".full_storyboard");
    var nar_name = $(this).closest('div').find(".my_narrative_name");
    var nar_text = $(this).closest('div').find(".complete_narrative");

    $("#full_complete").append($(storyboard).html() + " " + $(nar_name).html() + " " + $(nar_text).html());
    full = $(this).closest('div').find("#full_complete");
    $.when(generateImg()).then(restoreIt());
});

function generateImg(callback) {
    html2canvas($(full), {
        onrendered: function(canvas) {
            theCanvas = canvas;
            canvas.toBlob(function(blob) {
                saveAs(blob, + "your_storyboard.jpg"); //this works
            });
        }
    });
}

function restoreIt() {
    $("#full_complete").hide();
    $('#gen_narr').show();
    console.log('restore'); //this works
}

Solution

  • You not actually using promises/deferreds here since your generateImg or restoreIt doesn't return anything. you need to create promise inside generateImg that will be resolved inside onrendered

    Try something like this

    function generateImg(callback) {
        var dfd = jQuery.Deferred();
    
        html2canvas($(full), {
            onrendered: function(canvas) {
                theCanvas = canvas;
                canvas.toBlob(function(blob) {
                    saveAs(blob, + "your_storyboard.jpg"); //this works
                });
    
                dfd.resolve( "hurray" );
            }
        });
    
        return dfd.promise();
    }