Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Turn image into Data URL and save in localStorage
// 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);
@nevf

This comment has been minimized.

Copy link

nevf commented Oct 2, 2013

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.

@Hengjie

This comment has been minimized.

Copy link

Hengjie commented Apr 12, 2014

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

@plumpNation

This comment has been minimized.

Copy link

plumpNation commented Jun 14, 2014

https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image

Either I'm misreading or you need to allow CORS from the image server to allow this technique to work.

@rajashekhargundeti

This comment has been minimized.

Copy link

rajashekhargundeti commented Jul 30, 2015

what is 'localStorage' is referring to?? what kinda object is this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.