Search code examples
javascriptjquerycanvashtml2canvas

Changing a .click function button to load right away instead?


I'm loading html2canvas which has the following script:

 $(function() {
             $("#btnSave").click(function() {
                                 html2canvas($(".widget"), {
                                             onrendered: function(canvas) {
                                             theCanvas = canvas;
                                             document.body.appendChild(canvas);

                                             // Convert and download as image
                                             Canvas2Image.saveAsPNG(canvas);
                                             $("#img-out").append(canvas);
                                             // Clean up
                                             //document.body.removeChild(canvas);
                                             }
                                             });
                                 });
             });

I have a button with the id "btnSave" that when clicked it generates my canvas image. Now, instead of having to click the button I would prefer it to load on the page automatically. Is this possible?

jsFiddle to what I'm working with: https://jsfiddle.net/h5ase09f/

Thanks in advance!


Solution

  • Try doing it after the document loads using the ready callback:

    $(document).ready(function(){
         html2canvas($(".widget"), {
           onrendered: function(canvas) {
             theCanvas = canvas;
             document.body.appendChild(canvas);
    
             // Convert and download as image
             Canvas2Image.saveAsPNG(canvas);
             $("#img-out").append(canvas);
             // Clean up
             //document.body.removeChild(canvas);
           }
         });
    });