How to save and load HTML5 Canvas to & from localS

2019-06-13 03:55发布

问题:

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.

回答1:

First 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 recommend 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();
});


回答2:

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.