html5 canvas toDataURL返回空白图像

Eri*_*ick 4 javascript php html5 canvas data-url

从空白画布开始:

<canvas id='myCanvas' width='800' height='600'></canvas>
Run Code Online (Sandbox Code Playgroud)

然后初始化该画布:

  function init_canvas(){
    var canvas = document.getElementById('myCanvas');
    context = canvas.getContext('2d');
    context.lineCap = 'round';
    // fill it with white background
    context.save();
    context.fillStyle = '#fff';
    context.fillRect(0, 0, context.canvas.width, context.canvas.height);
    context.restore();
    return;
  }
Run Code Online (Sandbox Code Playgroud)

然后在画布上做一堆绘图.

然后尝试使用后端的ajax和PHP将其保存到服务器.

在客户端:

var img = canvas.toDataURL('image/png');
// strip the leading garbage.
img.substr(img.indexOf(',')+1).toString();
Run Code Online (Sandbox Code Playgroud)

将生成的字符串(base64编码的png)直接输入到PHP和base64_decode()字符串...图像总是正确的大小,但它没有任何绘图 - 只是一个透明的图像.这似乎不是PHP中的base64_decode()的问题,它似乎是一个安全的事情.Firefox 4和最新的Chrome都失败了.

使用"image/png"标头将生成的png图像转储到firefox会在错误控制台中生成:

Error: Image corrupt or truncated: http://somewhere.com/showimage.php
Source file: http://somewhere.com/showimage.php
Run Code Online (Sandbox Code Playgroud)

但是......除非toDataURL()在任何地方都被破坏,否则图像不会被破坏或被截断,因为php的东西只是base64_decode()toDataURL()的结果.

有任何想法吗?

谢谢!

rob*_*rtc 7

您是否在PHP文档中看到过此评论base64_decode

如果要保存从Javascript canvas.toDataURL()函数派生的数据,则必须将空格转换为加号.如果不这样做,解码数据将被破坏:

<?php
  $encodedData = str_replace(' ','+',$encodedData);
  $decocedData = base64_decode($encodedData);
?>
Run Code Online (Sandbox Code Playgroud)