是否可以将整个画布保存到本地存储并从本地存储中检索画布

时间:2014-05-28 12:04:25

标签: javascript html5 canvas

是否可以将整个画布保存到本地存储并从本地存储中检索画布。

我正在尝试使用以下代码

function saveBoard(e) {
    var canvas = document.getElementById("canvid1");
    var context = canvas.getContext("2d");
    context.save();   

    var drawingSurfaceImageData = context.getImageData(
        0, 0,
        canvas.width,
        canvas.height);

    if (typeof (localStorage) !== "undefined") {
        localStorage.setItem('imgCanvas',drawingSurfaceImageData);
    } else {
        document.getElementById("save").innerHTML.dataURL = "Local Storage not supported";
    }   
}

function restoreBoard() {
    alert("in restore");
    var canvas = document.getElementById("canvid1");
    var context = canvas.getContext("2d");
    var  data = localStorage.getItem("imgCanvas");
    alert("data"+data);
    context.putImageData(data, 0, 0);
}

1 个答案:

答案 0 :(得分:0)

是的,这应该是可能的。请记住,一个来源的本地存储不允许大于5MB!您可以在此site上测试浏览器的容量。您还应该检查您尝试从本地存储中获取的项目是否未定义。

function restoreBoard() {

  var canvas = document.getElementById("canvid1"),
      context = canvas.getContext("2d"),
      data = localStorage.getItem("imgCanvas");

  if(data){
    context.putImageData(data, 0, 0);
  }else{
    console.log('No data saved.')
  }

}

编辑:

也不存储图像数据,存储base64编码图像。您可以通过以下方式实现此目的:

function saveBoard(e) {
  var canvas = document.getElementById("canvid1"),
      context = canvas.getContext("2d");

  context.save();   

  var imageBase64String = canvas.toDataURL(); // get the base64 string from the canvas context

  if (typeof (localStorage) !== "undefined") {
    localStorage.setItem('imgCanvas',imageBase64String );
  } else {
    document.getElementById("save").innerHTML.dataURL = "Local Storage not supported";
  }   
}

然后按以下方式恢复:

function restoreBoard() {

  var canvas = document.getElementById("canvid1"),
      context = canvas.getContext("2d"),
      data = localStorage.getItem("imgCanvas");

  if(data){
    context.drawImage(data, 0, 0); // draw the base64 encoded image on the canvas
  }else{
    console.log('No data saved.')
  }

}