public
Last active

Turn image into Data URL and save in localStorage

  • Download Gist
image-data-url-localStorage.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
// 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);

Note that this only works if the JS is running on the same site as the image, otherwise you'll get a CORS security error.

You can fix that CORS issue by defining crossOrigin attr with anonymous in elephant

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.