简体   繁体   English

如何将HTML5 Canvas保存到localStorage并从中加载?

[英]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. 我建议使用canvas.toDataURL()而不是ctx.getImageData()因为ctx.getImageData() JSON字符串大小即使画布为空也将非常大。

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: 如果要将画布存储为lines数组,则应将line coords存储在某个变量中并保存其json:

localStorage.setItem(canvasName, JSON.stringify(linesArray));

Then you can load lines array and redraw canvas: 然后,您可以加载lines数组并重新绘制画布:

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: 现在将其stringifying后存储到localStorage

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. 关于localStorage ,你可以读这个这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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