|
//This example is using canvs toDataURL method for getting image data |
|
//Save image for offline useage |
|
localstorage_image_cache("722c-e69a-c6db"); |
|
//Save image in local storage |
|
function localstorage_image_cache(graphic_image_component_id) { |
|
//Return if browser is not firefox |
|
if (typeof InstallTrigger == 'undefined') return; |
|
// localStorage with image |
|
var storage_files = JSON.parse(localStorage.getItem(graphic_image_component_id)) || {}, |
|
//Get Image |
|
graphic_image = document.querySelector("#component-" + graphic_image_component_id + " img"); |
|
//if image selector in not valid |
|
if(!graphic_image) return alert("Invalid images selector"); |
|
//Create a images |
|
var img = new Image(); |
|
img.crossOrigin = 'Anonymous'; |
|
img.src = graphic_image.src; |
|
$(img) |
|
.one('load', function() { |
|
if (img.complete && img.naturalHeight !== 0) { |
|
console.log("image loaded successfully") |
|
var imgCanvas = document.createElement("canvas"), |
|
imgContext = imgCanvas.getContext("2d"); |
|
|
|
// Make sure canvas is as big as the picture |
|
imgCanvas.width = graphic_image.width; |
|
imgCanvas.height = graphic_image.height; |
|
|
|
// Draw image into canvas element |
|
imgContext.drawImage(img, 0, 0, graphic_image.width, graphic_image.height); |
|
|
|
// Save image as a data URL |
|
storage_files.graphic_image = imgCanvas.toDataURL("image/png"); |
|
|
|
// Set name for localStorage |
|
storage_files.src = img.src; |
|
|
|
// Save as JSON in localStorage |
|
try { |
|
localStorage.setItem(graphic_image_component_id, JSON.stringify(storage_files)); |
|
} |
|
catch (e) { |
|
console.log("Storage failed: " + e); |
|
} |
|
} |
|
else { |
|
//Get iamge from local storage |
|
$(graphic_image).attr({ |
|
'src': storage_files.graphic_image |
|
}); |
|
} |
|
}) |
|
.on('error', function() { |
|
// Use image from localStorage |
|
$(graphic_image).attr({ |
|
'src': storage_files.graphic_image |
|
}); |
|
}); |
|
} |