I want the user to be able to save canvas drawings to the localStorage (using the Save button)under a custom name and then be able to load (using the load button) previous drawings from the localStorage.
I want the user to be able to save canvas drawings to the localStorage (using the Save button)under a custom name and then be able to load (using the load button) previous drawings from the localStorage.
Share Improve this question asked Dec 10, 2013 at 23:27 user3088233user3088233 511 gold badge2 silver badges4 bronze badges 2- Here's my canvas: jsfiddle/Eyf23/2 – user3088233 Commented Dec 10, 2013 at 23:28
- hacks.mozilla/2012/02/… – Andy Commented Dec 10, 2013 at 23:37
2 Answers
Reset to default 11First option
If you want to save just a bitmap then you can save it this way:
localStorage.setItem(canvasName, canvas.toDataURL());
and then load like this:
var dataURL = localStorage.getItem(canvasName);
var img = new Image;
img.src = dataURL;
img.onload = function () {
ctx.drawImage(img, 0, 0);
};
I remend to use canvas.toDataURL()
instead of ctx.getImageData()
because ctx.getImageData()
JSON string size will be just enormous even if canvas is empty.
Second option
If you want to store canvas as lines array then you should store lines coords in some variable and save it`s json:
localStorage.setItem(canvasName, JSON.stringify(linesArray));
Then you can load lines array and redraw canvas:
var lines = JSON.parse(localStorage.getItem(canvasName));
lines.forEach(function (line) {
ctx.beginPath();
ctx.strokeStyle = line.color;
ctx.moveTo(line.x1, line.y1);
ctx.lineTo(line.x2, line.y2);
ctx.stroke();
});
First step will be to get image data from canvas.
var imageData = myCtxt.getImageData(0,0,WIDTH,HEIGHT);
Now store it to localStorage
after stringifying
it:
localStorage.setItem(savekey, JSON.stringify(idt));
To read and set the data back you can use following:
var idt = localStorage.getItem(savekey) || null;
if (idt !== null) {
var data = JSON.parse(idt);
ctx.putImageData(idt, 0, 0);
}
I have put the functions to handle the functionality in your fiddle.
Regarding localStorage
you can read this and this questions.