我用 html5-canvas 画了一些东西。然后我想保存它,当再次加载页面时,我想将我保存的图像加载回 Canvas 。我成功地将数据保存到服务器中的文件中,但由于某种原因,这是一个奇怪的文件,无法通过ant软件打开,当然也不能通过我的 Canvas 打开。我将其保存为 png base64,但我尝试了其他不起作用的方法。
JavaScript 代码:
function save(){ //saves the canvas into a string as a base64 png image. jsvalue is sent to the server by an html form
var b_canvas = document.getElementById("a");
var b_context = b_canvas.getContext("2d");
var img = b_canvas.toDataURL("image/png");
document.classic_form.jsvalue.value = img;
}
// opens the image file and displays it on the canvas
var canvas = document.getElementById("a");
var context = canvas.getContext("2d");
var img = new Image();
img.src = "backpicture.png";
img.onload = function() {
context.drawImage(img, 0, 0);
};
PHP 代码:
<?php
$str=$_POST['jsvalue'];
$file=fopen("backpicture.txt","w");
if(isset($_POST['submit']))
fwrite($file,$str);
fclose($file)
?>
它创建了文件,但当我再次加载页面时, Canvas 上没有显示任何内容。
我也尝试过使用 Canvas2Image.saveAsPNG()
,但仍然不起作用。
你能帮忙吗? 谢谢!
最佳答案
为了正确保存文件,您需要解码 Base64 数据(并保存为 png):
file_put_contents('backpicture.png', base64_decode($str));
关于php - HTML5 Canvas : How to save and reopen image from server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5571303/