简体   繁体   中英

How to save and load HTML5 Canvas to & from localStorage?

我希望用户能够以自定义名称将画布图形保存到localStorage (使用“保存”按钮),然后能够从localStorage加载(使用“加载”按钮)以前的图形。

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM