Save a browser cached image

2

I have several% tag img in my html, and the src is an external route to my server, every time I reload the page I must wait for the images to load, I know that the LocalStorage exists but I do not know how to save the image as such, I have only been able to save the link

    
asked by darioxlz 12.09.2018 в 03:41
source

1 answer

2

What you want to do is possible thanks to the fact that you can save the image as Base64, I will show you how, this answer is not mine but it works, it is posted in StackOverflow in English see link

First of all, I take my getElementByID image and save the image as Base64. Then I save the Base64 string as my localStorage value.

bannerImage = document.getElementById('bannerImg');
imgData = getBase64Image(bannerImage);
localStorage.setItem("imgData", imgData);

Here is the function that converts the image to Base64:

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

Then, on my next page, I created an image with a blank src:

<img src="" id="tableBanner" />

And directly when the page loads, I use the following three lines to get the base64 string from localstorage and apply it to the image with the blank src that I created:

var dataImage = localStorage.getItem('imgData');
bannerImg = document.getElementById('tableBanner');
bannerImg.src = "data:image/png;base64," + dataImage;
  

I edit to add how to verify if the variable does not exist;

if (localStorage.getItem("mi_variable") === null) {
  //Aqui se ejecuta todo si no existe
}

This does not work with gif since gifs are not compatible with canvas

    
answered by 12.09.2018 в 04:21