HERE您可以找到有关该主题的完整文章。但这里是简短的版本和源代码:
首先你需要将canvas二进制数据转换为base 64编码的字符串发送到服务器:
var image = canvas.toDataURL("image/png");
使用 ajax 调用发送:
var ajax = new XMLHttpRequest();
ajax.open("POST",'save.php', false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(image);
最后 PHP 脚本 save.php 看起来像这样:
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$fp = fopen( 'test.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
?>
PHP 脚本解析原始帖子数据,将 base 64 转换为二进制,并保存到文件中。有关 Base 64 的更多信息,请查看 THIS Wikipedia 文章。