使用html2canvas将画布与背景图像保存到服务器

Saving canvas with background image to server with html2canvas

本文关键字:图像 保存 服务器 背景 html2canvas 使用      更新时间:2023-09-26

我目前有一个脚本,通过使用html2canvas成功地从画布创建图像,包括其包含div背景图像。我也有一个脚本,可以保存画布作为一个图像到服务器使用canvas2image插件,但背景不显示。

我遇到的问题是,当我试图将两者结合起来,以便我可以将Div bg和画布保存为图像到服务器时,没有发生任何事情,我认为这是由于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]));
?>

我希望能够结合两个插件一起工作,让我的画布与Div背景保存到服务器,但它看起来像canvas2image插件不火。

谢谢!

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

作为一个题外话,我不知道为什么你使用一个插件来做任何你可以免费获得的原生画布API。

danders 说:"顺便说一句,我不知道你为什么要用插件来做任何你可以免费获得的原生画布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()