HTML5 Canvas图片上传 - 上传空白图片或销毁

时间:2017-03-19 18:29:05

标签: javascript php ajax html5 html5-canvas

我正在使用下面的代码混合两个图像并将其作为新的单个图像上传到服务器。为此,我使用的是Canvas。

我的HTML代码是:

<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var img1 = loadImage('https://xxxdomain.com/image1.jpg', main);
var img2 = loadImage('https://xxxdomain.com/image2.jpg', main);

var imagesLoaded = 0;
function main() {
    imagesLoaded += 1;

    if(imagesLoaded == 2) {
        // composite now
        ctx.drawImage(img1, 0, 0);

        ctx.globalAlpha = 0.5;
        ctx.drawImage(img2, 0, 0);

    }


    var myimage = canvas.toDataURL();
    var datasendervars = "myimage="+ myimage;
    alert(myimage);
    $.ajax({  
    type: "POST",
    url: "save.php",
    data: datasendervars,
    cache: false,  
    success: function(html){
        alert(html);

       }
});

}

function loadImage(src, onload) {
    var img = new Image();
    img.onload = onload;
    img.src = src;
return img;
}
<script>

<canvas width="700" height="367" id="canvas"></canvas>

我的上传php脚本是:

$img = $_POST['myimage'];
  $img = str_replace('data:image/png;base64,', '', $img);
  $img = str_replace(' ', '+', $img);
  $data = base64_decode($img);
  $file = 'tester/img'.date("YmdHis").'.png';

  if (file_put_contents($file, $data)) {
     echo "<p>The canvas was saved as $file.</p>";
  } else {
     echo "<p>The canvas could not be saved.</p>";
  }

图片上传成功,但其空白和所有上传的图片都是相同的文件大小。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您正在错误地发送 ajax发布请求。它应该是......

$.ajax({
    type: "POST",
    url: "save.php",
    data: {"myimage": myimage},
    cache: false,
    success: function(html) {
        alert(html);
    }
});

** 还确保图片托管在您的本地服务器(同一个域)