如何保存和加载HTML5画布到&从localStorage? [英] How to save and load HTML5 Canvas to & from localStorage?

查看:158
本文介绍了如何保存和加载HTML5画布到&从localStorage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望用户能够在自定义名称下的 localStorage (使用保存按钮)中保存画布图,然后可以使用加载按钮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.

推荐答案

第一个选项



位图,然后你可以这样保存:

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

我建议使用 canvas.toDataURL() ctx.getImageData()而不是 ctx.getImageData() JSON字符串大小将是巨大的,即使canvas

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存储为lines数组,在某些变量中保存它的json:

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

然后可以加载行数组和重绘canvas:

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

这篇关于如何保存和加载HTML5画布到&从localStorage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆