Base storage64 in localstorage

Well, I have a function in javascript:

function store_data(){ var img=document.createElement("img"); /*var img=new Image(); img.onload = function() { context.drawImage(img, 0, 0); };*/ img.src= URL; //js global var var height=parseInt(img.naturalHeight,10); var width=parseInt(img.naturalWidth,10); var canvas = document.getElementById('myCanvas'); canvas.setAttribute("width", width); canvas.setAttribute("height", height); var context = canvas.getContext('2d'); context.drawImage(img,0,0); canvas.style.width="100%"; var data=(canvas.toDataURL("image/png")); localStorage.setItem("data", data); } 

The first time a string of type "data;" is called in localStorage, an incomplete image is similar to "data64; aotehtahotetav ...". But when I call the second time, the data is kept in order. Why is this happening?

Maybe I need to upload the image to img from dom? The image is saved for use at the end.

+4
source share
2 answers

As Michael already mentioned, your code stores image data in localStorage before it is fully loaded. The second time the image already exists in the cache.

Perhaps try loading the image onto the canvas when the onload event fires like this

 function store_data() { var img = new Image(); img.src = URL; //js global var img.onload = function( ) { var canvas = document.getElementById( 'myCanvas' ); canvas.setAttribute( "width", img.width ); canvas.setAttribute( "height", img.height ); var context = canvas.getContext( '2d' ); context.drawImage( img, 0, 0 ); canvas.style.width = "100%"; var data = canvas.toDataURL("image/png"); localStorage.setItem( "data", data ); } } 
+3
source

If you do not store data in img.onload , you cannot be sure that the image data was fully loaded when you store it in local storage and you will get inconsistent data lengths.

0
source

All Articles