用localstroage缓存图片信息

总体的思想就是请求到图片之后,用canvas把图片画下来,然后借助canvas的toDataURL Api来把图片保存成base64的形式

let src = "";  //网络图片路径

 

function set(key) {

let img = document.createElement('img');

img.addEventListener('load', function() {

let imgCanvas = document.createElement('canvas');

imgContext = imgCanvas.getContext('2d');

imgCanvas.width = this.width;

imgCanvas.height = this.height;

imgContext.drawImage(this, 0, 0, this.width, this.height);

let imgAsDataURL = imgCanvas.toDataURL("image/png");

try {

localStorage.setItem(key, imgAsDataURL);

} catch(e) {

console.log("Storage failed:", e);

}

})

img.src = src;

}

 

function get(key) {

let srcStr = localStorage.getItem(key);

let imgObj = document.createElement('img');

imgObj.src = srcStr;

document.body.appendChild(imgObj);

}

你可能感兴趣的:(用localstroage缓存图片信息)