K
K
Kusmich2015-10-28 02:09:25
css
Kusmich, 2015-10-28 02:09:25

How to re-encode to base64 and push elements created dynamically into local-storage?

Recently there was a question about how to push pictures into local storage and then from there, get them and display them in the DOM. I took the code, modified it and everything worked.

But my task is that all elements in the DOM are created dynamically. The problem is that a script that worked with normal DOM elements doesn't want to work with dynamically created elements.

Here is the image code that creates them dynamically:

console.log(masive_picture)
var idint = 0;
var masive_picture = [
  "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Proton-K-Zarya.jpg/800px-Proton-K-Zarya.jpg",
  "https://upload.wikimedia.org/wikipedia/ru/3/31/Winniethepooh.jpg"
];
var box = $("body");
for (var i = 0; i < masive_picture.length; i++) {
  idint++;
  console.log(idint)
  box.append('<img class="tableBanner1" src="' + masive_picture[i] + '">')
    // $(".tableBanner").attr("id", idint);	
}
box.append('<img class="tableBanner" id="tableBanner0"   src="">')
box.append('<img class="tableBanner" id="tableBanner1"   src="">')
})

Here is the code that writes and retrieves from the repository:
$(document).ready(function() {
  function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
  }

  var els = document.getElementsByClassName("tableBanner1");
  var imgCnt = 0;

  Array.prototype.forEach.call(els, function(bannerImage) {
    // Do stuff with the element
    console.log(bannerImage);
    if (bannerImage.width > 0) {
      imgData = getBase64Image(bannerImage);
      localStorage.setItem("imgData" + imgCnt, imgData);

      var dataImage = localStorage.getItem('imgData' + imgCnt);
      bannerImg = document.getElementById('tableBanner' + imgCnt);
      bannerImg.src = "data:image/png;base64," + dataImage;
      imgCnt++;
    }

  });

});


Tell me what I'm doing wrong? And how should it?

Here is the fiddle where all the code is: https://jsfiddle.net/85q5vq4k/3/

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2015-10-28
@Stalker_RED

So I run your code, and the first thing I see in the chrome console is -

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

From the first attempt of Google, it turns out that he canvas.toDataURLdoes not want to work with pictures pulled from another domain.
You need to either post pictures on your own or use CORS.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question