5

I need to save all drawings from my canvas in order to be able to return to them later on.

I succeed in getting and putting data but I can't save the object and return it correctly.

This is my code:

var imgData = a.getImageData(0, 0, 500, 200);
localStorage.setItem("test",JSON.stringify(imgData))
console.log(imgData)
console.log(JSON.parse(localStorage.getItem("test")))
b.putImageData(imgData, 0, 0);
Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
Albaz
  • 905
  • 12
  • 21

2 Answers2

4

You can use the canvas.toDataURL() method which will encode the canvas into Base64.

You can then create a image with the source being the data url and then draw that image to the canvas.

Here is the working sample.

var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');

var ctx = canvas.getContext("2d");

ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);

var url = canvas.toDataURL();

localStorage.setItem('url', url);

var canvas2 = document.getElementById('tutorial2');
var ctx2 = canvas2.getContext("2d");
var toDrawUrl = localStorage.getItem('url');

drawDataURIOnCanvas(toDrawUrl, ctx2);
ctx2.fillStyle = "rgb(200,200,0)";
ctx2.fillRect (20, 20, 55, 50);


function drawDataURIOnCanvas(strDataURI, context) {
    "use strict";
    var img = new window.Image();
    img.addEventListener("load", function () {
        context.drawImage(img, 0, 0);
    });
    img.setAttribute("src", strDataURI);
}
blessanm86
  • 31,439
  • 14
  • 68
  • 79
  • I have tried this already but i want to edit the shape in new canvas and save the shape again when i want if i used 'toDataURL' i cant remove or edit part in shape and save it again – Albaz Jan 04 '16 at 06:26
  • 1
    @Elbazz I assume u just want the the image data. Just get the image data after we draw the image on the canvas. Or this may give u an idea on serializing the image data http://stackoverflow.com/a/22233902/548568 – blessanm86 Jan 04 '16 at 06:33
  • 1
    thank you so much i success to save to local storage but by catch the full point your link help me and i put comment in it for this – Albaz Jan 17 '16 at 09:41
1

i want to save the huge data as imagedate in local-storage you must be convert from buffer to string and used this functions

    function buf2str(buf) {
       var bufView = new Uint16Array(buf);
       var unis =""
       for (var i = 0; i < bufView.length; i++) {
             unis=unis+String.fromCharCode(bufView[i]);
        }
       return unis
   }

to reverse function use this function

function str2buf(str) {
    var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
    var bufView = new Uint16Array(buf);
    for (var i=0, strLen=str.length; i<strLen; i++) {
        bufView[i] = str.charCodeAt(i);
    }
    return buf;
}

i has success to save data and edit it after callback

my code is

 var canvasData={
    _save:function(from,id){
        var imgData = from.getImageData(0, 0, el.width, el.height);
        var buffer = imgData.data.buffer;
        var testV=ab2str(buffer);

        try { 
            localStorage.setItem(id+"Length",testV._length)
            localStorage.setItem(id+"Keys",testV._keys)
            localStorage.setItem(id+"Data",testV._Data)
        } catch(e) {
            var storageSize = Math.round(JSON.stringify(localStorage).length / 1024);
            console.log("LIMIT REACHED: (" + i + ") " + storageSize + "K");
            console.log(e);
             alert("your localStorage is complete , you must delete some nots or markers to be can store again ")

    }


    },
    _return:function(to,id){
        var tempObj={_Length:0,_Keys:"",_Data:""}


         try {     
            tempObj._Length= localStorage.getItem(id+"Length")
            tempObj._Keys= localStorage.getItem(id+"Keys")
            tempObj._Data= localStorage.getItem(id+"Data")
        } catch(e) {
            var storageSize = Math.round(JSON.stringify(localStorage).length / 1024);
            console.log("LIMIT REACHED: (" + i + ") " + storageSize + "K");
            console.log(e);

    }

        if (tempObj ==null ){return false};
        if (tempObj._Length ==null ){return false};
        if (tempObj._Keys ==null ){return false};
         if (tempObj._Data ==null ){return false};
        var temp=tempObj._Length.split(",");
        var newWidth=parseInt(temp[0]);
        var newHeight= parseInt(temp[1]);
        var newImgData = to.createImageData(newWidth,newHeight);
        var incomingBuffer=returnOriginalBuffer(tempObj)
        newImgData.data.set(new Uint8Array(incomingBuffer))

        to.putImageData(newImgData, 0, 0);

    }
} 
function ab2str(buf) {
    var bufView = new Uint16Array(buf);
    var dataArr=new Array();
    var dataStr =""
    var keysStr =""
    var lenStr=el.width.toString()+","+el.height.toString()
    var returnedObj={_length:lenStr,_keys:"",_Data:""}
    var dote="";
    for (var q = 0; q < bufView.length; q++) {
        if(bufView[q]!=0){
            keysStr=keysStr+dote+q;
            dote=","
            dataArr.push(bufView[q]);
        } 
    }
    for (var w = 0; w < dataArr.length; w++) {
        dataStr=dataStr+String.fromCharCode(dataArr[w]);
    }

    returnedObj._keys=keysStr;
    returnedObj._Data=dataStr;


    return returnedObj
    }
function returnOriginalBuffer(tempObj) {
    var temp=tempObj._Length.split(",");
    var _length=parseInt(temp[0])*parseInt(temp[1])*2
    var _keys=tempObj._Keys;
    var _data=tempObj._Data;
    var keysArr =new Array();
    var dataArr=new Array();

    keysArr=_keys.split(",")
    for (var w=0, strLen=_data.length; w<strLen; w++) {
        dataArr[w]=_data.charCodeAt(w) ;
    }


    var buf = new ArrayBuffer(_length*2); // 2 bytes for each char
    var bufView = new Uint16Array(buf);
    var q=0
        for (var i=0, strLen=_length; i<strLen; i++) {
            if (i!=parseInt(keysArr[q])){
                bufView[i] = 0;
            }else{
                bufView[i] = dataArr[q]
                q++;

            }

        }

  return buf;
    }

  //save data
         canvasData._save(ctx,"localstoragename")
// return data
         canvasData._return(ctx,"localstoragename")

this soluation is complex if any one own simple workaround, help us

Albaz
  • 905
  • 12
  • 21