Search code examples
javascript

storing base64 in localstorage


I have the following javascript function called store_data:

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 the function is being called "data" in localStorage - is incomplete: "data64;aotehtahotetav...". When I call the function the second time the data is stored fine. Why does it show this behavior?

Should I load the image in a IMG after DOM is fully loaded?


Solution

  • Like Michael has already mentioned your code is saving the image's data to localStorage before it has completely downloaded. The second time the image already exists in cache.

    Maybe try loading the image onto the canvas when the onload event fires like so

    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 );
        }
    
    }