Search code examples
javascriptimagecanvassavehtml2canvas

Saving div to canvas to image (jpeg) and auto save in server


HTML: <div id='mydiv' name='mydiv' width='600' height='600' > <img src="clouds.png"></div>

$(document).ready(function () 
     {
        //alert("save pleaseeeee?");

        $("#save").click(function () 
        {
          html2canvas([document.getElementById('mydiv')],
          {
            onrendered: function (canvas) 
            {
              var canvas = document.getElementById('canvas');
              $.post("save.php", 
              {
                data: canvas.toDataURL("image/jpeg")
              }, 

              function (file) 
              {
                window.location.href =  "download.php?path="+ file
              });
            })
        });
        // end of onclick save
     });

The autosave works when converting a canvas to image only. I tried to merge it with the html2canvas function so that I can save div-canvas-image. Thanks!


Solution

  • You are overwriting the canvas element html2canvas is providing. Try to use that argument directly:

    onrendered: function (canvas) // <- use this argument
    {
      /// This is overwriting the rendered canvas
      //var canvas = document.getElementById('canvas');
      $.post("save.php", 
      {
        data: canvas.toDataURL("image/jpeg")
      }, 
    
      function (file) 
      {
        window.location.href =  "download.php?path="+ file
      });
    })
    

    From the documentation:

    The rendered canvas is provided in the callback event onrendered, as such:

    html2canvas(element, {
        onrendered: function(canvas) {
            // canvas is the final rendered <canvas> element
        }
    });