<canvas id="myCanvas" width="200" height="100"></canvas>
var canvas = document.getElementById('myCanvas');
var img = canvas.toDataURL('image/png');
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$filename = date('YmdHis').'.png';
$file = fopen('uploads/'.$filename, 'w');
fwrite($file, $data);
fclose($file);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas 圖像保存</title>
</head>
<body>
<canvas id="myCanvas" width="200" height="100"></canvas>
<button onclick="save()">保存圖片</button>
<script>
function save() {
var canvas = document.getElementById('myCanvas');
var img = canvas.toDataURL('image/png');
img = img.replace(/^data:image\/(png|jpg);base64,/, ''); // 去掉頭文件
img = img.replace(/\s/g, '+'); // 替換空格
$.post('save.php', {'imgBase64': img}, function(data) {
alert('保存成功!');
});
}
</script>
</body>
</html>
<?php
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$filename = date('YmdHis').'.png';
$file = fopen('uploads/'.$filename, 'w');
fwrite($file, $data);
fclose($file);
echo 'success';
?>