Sometimes, we want to save an image to localStorage and display it on the next page with JavaScript.
In this article, we’ll look at how to save an image to localStorage and display it on the next page with JavaScript.
How to save an image to localStorage and display it on the next page with JavaScript?
To save an image to localStorage and display it on the next page with JavaScript, we can create a canvas, put the image in it, and then convert the canvas data to a base64 string.
For instance, we write
const getBase64Image = (img) => {
const canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
const dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
};
const bannerImage = document.getElementById("bannerImg");
const imgData = getBase64Image(bannerImage);
localStorage.setItem("imgData", imgData);
to define the getBase64Image
function that creates the canvas element with createElement
.
Then we set the width and height of the canvas to the image width and height.
We draw the image on the canvas with drawImage
.
And then we call toDataURL
to return the base64 string with the canvas data.
Then we use it to encode the image to a string and save it to local storage with
const bannerImage = document.getElementById("bannerImg");
const imgData = getBase64Image(bannerImage);
localStorage.setItem("imgData", imgData);
We get the img element with getElementById
and then call getBase64Image
to get the data.
And then we call setItem
to save the imgData
to local storage.
Then on the destination page, we write
const dataImage = localStorage.getItem("imgData");
const bannerImg = document.getElementById("tableBanner");
bannerImg.src = "data:image/png;base64," + dataImage;
to get the local storage entry with getItem
.
And we select the image with getElementById
.
And then we set the src attribute of the img element with
bannerImg.src = "data:image/png;base64," + dataImage;
Conclusion
To save an image to localStorage and display it on the next page with JavaScript, we can create a canvas, put the image in it, and then convert the canvas data to a base64 string.