Blade,他们有很多不同的方法来做到这一点。我给你看一个 .With localstorage Json db。
您可以使用另一种方法,例如带有 XMLHttpRequest Level 2 的 Blob。
有关它的更多信息,您可以查看此链接
-> Saving images and filesin localStorage - javascript
存储图片(您首先需要使用 localStorage.SetItem 存储所有图片 ....)
这里的想法是能够获取已经加载到当前网页的图像并将其存储到localStorage。正如我们上面建立的,localStorage 只支持字符串,所以我们这里需要做的就是把图片变成一个Data URL。对图像执行此操作的一种方法是加载到画布元素中。然后,使用画布,您可以将画布中的当前视觉表示读出为数据 URL。
让我们看看这个例子,我们在文档中有一个 id 为“elephant”的图像:
// Get a reference to the image element
var elephant = document.getElementById("elephant");
// Take action when the image has loaded
elephant.addEventListener("load", function () {
var imgCanvas = document.createElement("canvas"),
imgContext = imgCanvas.getContext("2d");
// Make sure canvas is as big as the picture
imgCanvas.width = elephant.width;
imgCanvas.height = elephant.height;
// Draw image into canvas element
imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height);
// Get canvas contents as a data URL
var imgAsDataURL = imgCanvas.toDataURL("image/png");
// Save image into localStorage
try {
localStorage.setItem("elephant", imgAsDataURL);
}
catch (e) {
console.log("Storage failed: " + e);
}
}, false);
然后,如果我们想更进一步,我们可以利用 JavaScript 对象并使用 localStorage 进行日期检查。在这个例子中,我们第一次通过 JavaScript 从服务器加载图像,但之后每次页面加载,我们都从 localStorage 读取保存的图像:
HTML
<figure>
<img id="elephant" src="about:blank" alt="A close up of an elephant">
<noscript>
<img src="elephant.png" alt="A close up of an elephant">
</noscript>
<figcaption>A mighty big elephant, and mighty close too!</figcaption>
</figure>
JAVASCRIPT
// localStorage with image
var storageFiles = JSON.parse(localStorage.getItem("storageFiles")) || {},
elephant = document.getElementById("elephant"),
storageFilesDate = storageFiles.date,
date = new Date(),
todaysDate = (date.getMonth() + 1).toString() + date.getDate().toString();
// Compare date and create localStorage if it's not existing/too old
if (typeof storageFilesDate === "undefined" || storageFilesDate < todaysDate) {
// Take action when the image has loaded
elephant.addEventListener("load", function () {
var imgCanvas = document.createElement("canvas"),
imgContext = imgCanvas.getContext("2d");
// Make sure canvas is as big as the picture
imgCanvas.width = elephant.width;
imgCanvas.height = elephant.height;
// Draw image into canvas element
imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height);
// Save image as a data URL
storageFiles.elephant = imgCanvas.toDataURL("image/png");
// Set date for localStorage
storageFiles.date = todaysDate;
// Save as JSON in localStorage
try {
localStorage.setItem("storageFiles", JSON.stringify(storageFiles));
}
catch (e) {
console.log("Storage failed: " + e);
}
}, false);
// Set initial image src
elephant.setAttribute("src", "elephant.png");
}
else {
// Use image from localStorage
elephant.setAttribute("src", storageFiles.elephant);
}