HTML5 使用localStorage本地缓存图片

在网站上找到了一些localStorage的实例,但是都无法直接使用,研究了一下。现在把案例贴出来。

案例如下:


<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Access-Control-Allow-Origin" content="anonymous">
<title>locstorage 图片存储</title>
</head>

<body>

 <!--image1-->
 <img id="acc" src="about:blank" alt="A close up of an elephant">
 
</body>
</html>
<script>
<!--image1-->
var gsFiles = JSON.parse(localStorage.getItem("gsFiles")) || {};
var a = document.getElementById("acc");
gsFilesDate = gsFiles.date;

 date = new Date();
 todaysDate = (date.getMonth() + 1).toString() + date.getDate().toString();

// 检查数据,如果不存在或者数据过期,则创建一个本地存储
if (typeof gsFilesDate === "undefined" || gsFilesDate < todaysDate) {

 // 图片加载完成后执行
 
 <!--image1-->
 a.addEventListener("load", function () {

 var imgCanvas = document.createElement("canvas");
 imgContext = imgCanvas.getContext("2d");
// 确保canvas尺寸和图片一致
 imgCanvas.width = a.width;
 imgCanvas.height = a.height;
// 在canvas中绘制图片
 imgContext.drawImage(a, 0, 0, a.width, a.height);

// 将图片保存为Data URI
 gsFiles.a = imgCanvas.toDataURL("bj.png");

gsFiles.date = todaysDate;

// 将JSON保存到本地存储中
try {
localStorage.setItem("gsFiles", JSON.stringify(gsFiles));

}
catch (e) {
console.log("Storage failed: " + e);
}
}, false);
// 设置图片
a.setAttribute("src", "bj.png");
}
else {
// Use image from localStorage
a.setAttribute("src", gsFiles.a);
}
</script>



  
运行后,使用浏览器的开发者模式,可以再Resources里面的Local Storage(本地缓存)里面看到存进去的图片。

注:页面和图片一定要放在服务器里面,通过服务器来访问!便捷一点的可以使用phpStudy,把网页和图片放在WWW文件夹下面,就可以访问了

 例:http://localhost:8090/1111.HTML

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值