Search code examples
javascriptjqueryhtmlcanvashtml2canvas

Saving canvas with background image to server with html2canvas


I currently have a script that successfully creates an image from canvas including its containing Div background image by using html2canvas. I also have a script that can save the canvas as an image to the server using the canvas2image plugin but the background doesn't show up.

The problem I'm having is when I try to combine the two so that I can save the Div bg and canvas as an image to the server, nothing happens which I believe is due to the canvas2image plugin not firing.

The code I have with both plugins combined is here.

function exportAndSaveCanvas()  {

html2canvas($("#containingDiv"), { 
        background:'#fff',
        onrendered: function(canvas) { 

       // var imgData = canvas.toDataURL('image/jpeg'); <--This would create the image needed 
    //but I replaced with the line below to tie in the two plugins

        var screenshot = Canvas2Image.saveAsPNG(canvas, true);      

        canvas.parentNode.appendChild(screenshot);
        screenshot.id = "canvasimage";      
        data = $('#canvasimage').attr('src');
        canvas.parentNode.removeChild(screenshot);

        // Send the screenshot to PHP to save it on the server
        var url = 'upload/export.php';
        $.ajax({ 
            type: "POST", 
            url: url,
            dataType: 'text',
            data: {
                base64data : data
            }
        });

      }
   });

 }

The code for export.php which upload the image to the server is here

<?php


    $data = $_REQUEST['base64data']; 
    //echo $data;

    $image = explode('base64,',$data); 


    file_put_contents('../uploadimg/myImage.jpg', base64_decode($image[1]));

?>

I was hoping to be able to combine the two plugins to work together and get my canvas with Div background save to the server but it looks like the canvas2image plugin doesn't fire.

Thanks!


Solution

  • dtanders said "As an aside, I'm not sure why you're using a plugin to do anything you get for free with the native canvas API."

    This got me thinking that I was making it more difficult than it needed to be so I stripped away some code. The script below does just what I need.

    function exportAndSaveCanvas()  {
    
            html2canvas($("#containingDiv"), { 
            background:'#fff',
            onrendered: function(canvas) {         
               var imgData = canvas.toDataURL('image/jpeg');   
    
    
        var url = 'upload/export.php';
            $.ajax({ 
                type: "POST", 
                url: url,
                dataType: 'text',
                data: {
                    base64data : imgData
                }
            });     
            }
    
        }); //End html2canvas
        } // End exportAndSaveCanvas()