php - HTML5 Canvas : How to save and reopen image from server

标签 php javascript html file canvas

我用 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/

相关文章:

javascript - 使用 XPath foreach 进行 Google map 地理编码器

php - 如果表中没有值,则查询应返回 0

javascript - 任何应用程序都无法执行此选项 - 输入类型 ="file"

javascript - 无法读取 null 的属性 'offsetTop'

javascript - 一些空间,即使 padding 和 margin 设置为 0px

html - 使 HTML 下拉列表位于所有页面内容之上

php - 判断是否提交空$_POST

php - 扩展单例类

javascript - 在 IIFE 构造函数中使用 'This'

html - 如何像向左或向右浮动一样从中心开始 div?