Davy Karlsson
Davy Karlsson

Reputation: 887

Saving image in canvas to local storage

I'm trying to save my drawn circles on my canvas to the localstorage, but I just can't get it to work, at all.

So far this is my save-code in JS.

function saveCanvas() {
var canvas = document.getElementById("imgCanvas"),
    doomslayer = canvas.toDataURL();

 if (typeof (localStorage) !== "undefined") {

    localStorage.setItem('imgCanvas', doomslayer);
 } else {
    document.getElementById("save").innerHTML.dataURL = "Local Storage not supported";
   }
}

function loadCanvas() {

var image = localStorage.getItem('imgCanvas');

document.getElementById('imgCanvas').src = image;
}

JSFiddle link

Got it to work now, finally! Working fiddle :)

Upvotes: 2

Views: 5804

Answers (1)

markE
markE

Reputation: 105015

You must load the saved data url into an Image and then use drawImage to load it onto the canvas

IE limitation: localStorage is only available on a served page (local execution won't work!).

// save to localStorage

localStorage.setItem("imgCanvas",canvas.toDataURL());

// reload from localStorage

var img=new Image();
img.onload=function(){
    context.drawImage(img,0,0);
}
img.src=localStorage.getItem("imgCanvas");

Upvotes: 3

Related Questions