使用 html2canvas 将带有背景图片的 canvas 保存到服务器

Saving canvas with background image to server with html2canvas

我目前有一个脚本可以使用 html2canvas 从 canvas 成功创建图像,包括其包含的 Div 背景图像。我还有一个脚本可以使用 canvas2image 插件将 canvas 作为图像保存到服务器,但背景没有显示。

我遇到的问题是当我尝试将两者结合起来以便我可以将 Div bg 和 canvas 作为图像保存到服务器时,我认为没有任何反应由于 canvas2image 插件未触发。

我结合了两个插件的代码在这里。

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
            }
        });

      }
   });

 }

上传图片到服务器的export.php代码在这里

<?php


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

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


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

?>

我希望能够将这两个插件结合起来一起工作,并将我的 canvas 和 Div 后台保存到服务器,但它看起来像 canvas2image 插件不开火。

谢谢!

先将背景图片写入 canvas,然后再写入其他图片。关于将图像写入 canvas 的 MDN 页面应该涵盖了:https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images

顺便说一句,我不确定您为什么要使用插件来免费使用本机 canvas API.

dtanders 说 "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."

这让我觉得我让它变得比需要的更难,所以我去掉了一些代码。下面的脚本正是我所需要的。

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()