Answer the question
In order to leave comments, you need to log in
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="">')
})
$(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++;
}
});
});
Answer the question
In order to leave comments, you need to log in
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.
canvas.toDataURL
does not want to work with pictures pulled from another domain. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question