0

I made this code to take images from the page, convert them into data:url (what was it again... base64 encoded string), and save into localStorage. Then when the page is reloaded it should load the images from the localstorage and set the now empty image placeholders with the data:url image.

Issue now is that the images do not load and if you check the dimensions for the data:url image it is 300x150 when it was originally 40x40.

Here's the code:

var isChached, // Checks is the page's images have been chached into localStorage
    isChangesd;     // Checks if any images have been deleted or added to the
    var img = [],  // Used for loading from saved. img[] holds data:url image versions of the...
    src = [],      // ...images in src[]
    saved = [],    // All images that are to be saved are placed here
    add = [],      // New images are placed here
    rem = [];      // Images to be removed are placed here
    var cnv = document.createElement("canvas");
    ctx = cnv.getContext("2d");

  if (window.localStorage) {
    // Base Object
    function Saver (width,height,path) {
      this.width = width;
      this.height = height;
      this.src = path;
    }

    // These fucnctions will help you save, load, and convert the images to data:url
    function save (_str) { // Saves to localStorage. _str is the key to which to save to. _path is the value that you plan on saving
      var str = _str;
      str += "";   // This way even if I input a none string value it is still converted into string
      localStorage.setItem(str,JSON.stringify(saved));
    } // Checks if this image isn't in the saved cache

    function singleLoad(a,b) {

    }

    function loader (_str) { // Loads images from localStorage. _str is the key to be loaded
      var str = _str;
      str += "";   // This way even if I input a none string value it is still converted into string
      var val = JSON.parse(localStorage.getItem(str)); // Save the now loaded and parsed object str into val
      console.log('val '+JSON.stringify(val));
      val.splice(0,1);
      console.log('val2 '+JSON.stringify(val));
      for (var i in val) { // Take loaded information and place it into it's proper position
        img[i] = new Image(val[i].width,val[i].height);
        img[i].src = val[i].src;

        setTimeout(function () {
          var imgs = document.getElementsByTagName("img"); // Get all images
          for (var k = 0; k < imgs.length; k++) {
            if (imgs[i].id == i) { // If the id is equal to the index name of the src[]
              imgs[k].src = val[i].src;
              imgs[k].height = img[i].height;
              imgs[k].width = img[i].width;
              console.log("array: "+imgs[i]+". img[i]"+img[i]);
            }
          }
        },2000);
      }
    }
    function addToAdd(_id,_path) { // Places on-page images into src[]
      var id = _id;
      id += "";   // Makes sure that the id variable is a string
      var path = _path;
      path += ""; // Makes sure that the path variable is a string
      add[id] = new Image();
      add[id].src = path;
      var imgs = document.getElementsByTagName("img");
      console.log(imgs);
      for (var i = 0; i < imgs.length; i++) { // adds width and height attributes
        if (imgs[i].id == id) {
          setDim(add[id],imgs[i].width,imgs[i].height); // Send info to setDim()
        }
      }
    }

    // Not using this
    function apply() { // takes images from img after being loaded and adds them to the page.
      var images = document.getElementsByTagName("img");
      for (var i = 0; i < images.length; i++) { // Check through the page's images
        for (var k in img) { // Check through the img[] where the loaded images are now saved
          if (images[i].id = k) { // Check if the id of the image on the page is
            images[i].width = img[k].width;
            images[i].height = img[k].height;
            images[i].src = img[k].src;
            console.log("source: "+images[i].src);
            console.log("images: "+images[i]+". saved images "+img[k]);
          }
        }
      }
    }

    function setDim(obj,w,h) { // Sets the dimension(width = w; height = h;) for obj (image object)
      obj.width = w;
      obj.height = h;
    }

    function saveToSrc(_id,_path,w,h) { // Places on-page images into src[]
      var id = _id,data;
      id += "";   // Makes sure that the id variable is a string
      var path = _path;
      path += ""; // Makes sure that the path variable is a string
      src[id] = new Image();
      src[id].src = path;
      console.log("src image " + src[id]);
      var imgs = document.getElementsByTagName("img");
      console.log("page images " + imgs);
      for (var i = 0; i < imgs.length; i++) { // adds width and height attributes
        if (imgs[i].id == id) {
          setDim(src[id],imgs[i].width,imgs[i].height); // Send info to setDim()

          src[id].addEventListener("load",function() { // We convert images to data:url
            console.log("saved image " + src);
            ctx.drawImage(src[id],0,0,w,h);
            data = cnv.toDataURL();
            console.log("saved src " + data +" src width and height: "+src[id].width+","+src[id].height);
            saved[id] = new Saver(src[id].width + "px",src[id].height + "px",data);
            console.log("saver array: "+saved[id]);
          })
        }
      }
    }

    function loadToPage(a) {
      var imgs = document.getElementsByTagName("img"); // Get all images. Use this to change image src and dimensions

      for (var i in a) { // Go through the a[] and load all the images inside onto page
        for (var k = 0; k < imgs.length; k++) {
          if (imgs[k].id == i) {
            imgs[k].src = a[i].src;
            imgs[k].height = a[i].height;
            imgs[k].width = a[i].width;
          }
        }
      }
    } 

    // Here you place ID and path/location values into the src[] using the saveToSrc(). You can place the parameters in with quotation marks or without quotation marks
    // **N.B** the location link will have to be changed to it's absolute form so that even if a 'scraper' gets our webpage the links still come to us \o/


    if (localStorage.getItem("cached") == null) { // Check if the "cached" key exists.
      // If it doesn't exist...

      isCached = false;
      localStorage.setItem("cached","true");
    } else {
      // ...If it does exist
      isCached = true;
    }

    if (!isCached) {
      // Now you take images from server and load onto page. And then save them.



      window.onload = function() {

    saveToSrc("1","img/1.png",40,40);
    saveToSrc("2","img/2.png",40,40);
    saveToSrc("3","img/3.png",40,40);
    saveToSrc("4","img/4.png",40,40);
    console.log("src "+src);
    console.log("saved array " + saved);

        loadToPage(src);
        setTimeout(function() {
          save('saved');
        },3000)

      }
    }
    /* Will Be Added Later. Same time as local host */
    else {
      window.onload = function (){
        setTimeout(function() {
          loader("saved");
          apply
        },3000)

      }
    }
  }

I'm quite new to javascript(started using javascript this June, or was it May. anyways...) so please relax on the terminology.

To recap: Images saving correctly(-ish), not loading, and wrong image sizes saved

Kitanga Nday
  • 3,517
  • 2
  • 17
  • 29
  • I know this doesn't answer your question, but it might be a better approach: http://stackoverflow.com/questions/1285354/how-to-force-a-web-browser-to-cache-images – Adam Zerner Nov 27 '15 at 06:26
  • @AdamZerner thanks for the suggestion, but I plan on using this method. – Kitanga Nday Nov 27 '15 at 14:46
  • Ok. I'm curious - how come? I don't know much about using local storage for this. Is it faster? – Adam Zerner Nov 27 '15 at 16:46
  • @AdamZerner check out this link [localstorage faster than browser cache on mobile](http://www.mobify.com/blog/smartphone-localstorage-outperforms-browser-cache/) – Kitanga Nday Nov 30 '15 at 08:28
  • Interesting, thanks for sharing. I'm sure you already know this from reading the article, but a) make sure you have enough memory, and b) make sure speed really is important enough for your app to justify the added complexity and developer effort. – Adam Zerner Nov 30 '15 at 16:21

0 Answers0