以下是如何实现您的需求的示例:
1)画一些东西(取自画布教程)
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// begin custom shape
context.beginPath();
context.moveto(170,80);
context.bezierCurveto(130,100,130,150,230,150);
context.bezierCurveto(250,180,320,340,150);
context.bezierCurveto(420,420,120,390,100);
context.bezierCurveto(430,40,370,30,50);
context.bezierCurveto(320,5,250,20,50);
context.bezierCurveto(200,170,80);
// complete custom shape
context.closePath();
context.linewidth = 5;
context.fillStyle = '#8ED6FF';
context.fill();
context.strokeStyle = 'blue';
context.stroke();
2)将画布图像转换为URL格式(base64)
var dataURL = canvas.toDataURL();
3)通过Ajax将其发送到您的服务器
$.ajax({
type: "POST",
url: "script.PHP",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
// If you want the file to be visible in the browser
// - please modify the callback in javascript. All you
// need is to return the url to the file,you just saved
// and than put the image in your browser.
});
3)将base64保存在服务器上作为图像
$img = $_POST['data'];
$img = str_replace('data:image/png;base64,','',$img);
$img = str_replace(' ','+',$img);
$fileData = base64_decode($img);
//saving
$fileName = 'photo.png';
file_put_contents($fileName,$fileData);