Hello, it's my debut on SO, although I've been a regular user for quite some time and found all the answers I needed here...until now.
I'm currently grappling with an intricate issue involving XHR. While I consider myself a bit of a JS newbie, I never anticipated facing this particular challenge and I'm struggling to overcome it...
The crux of the matter is that I'm fetching a series of images from a remote server using a "for" loop. This part is functioning smoothly. However, I aim to assign them unique IDs to be able to manipulate them sequentially in a canvas for animation purposes. The problem arises with incrementing the ID properly. Here's a snippet of my code :
<body>
<button onclick="loadCanvas(113);">Click here</button>
<canvas id="targetedCanvas" width="768" height="512"></canvas>
<script>
window.URL = window.URL || window.webkitURL;
function loadImages() {
for (id = 0; id < 114; id++) {
var url = 'http://myurl.com/IMG_'+id+'.JPG';
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'blob';
request.onload = function(e) {
if(this.status == 200) {
var blob = this.response;
var img = document.createElement('img');
img.id = id;
img.onload = function(e) {
window.URL.revokeObjectURL(img.src);
};
img.src = window.URL.createObjectURL(blob);
img.width = 0;
img.height = 0;
document.body.appendChild(img);
}
}
request.send(null);
};
}
function loadCanvas(id) {
var canvas = document.getElementById('targetedCanvas');
var context = canvas.getContext('2d');
var img = document.getElementById(id);
context.drawImage(img,0,0);
};
loadImages();
</script>
</body>
As you can observe, there's a button that loads the image onto the canvas upon clicking.
When attempting to display the ID (console.log(id);
), it functions correctly outside the request.onload function (i.e., increments as expected like 1, 2, 3...). However, inside the function, it stays fixed at 113. This discrepancy baffles me. I presume it has something to do with XHR being asynchronous or similar complexities – areas where my understanding is limited.
If anyone possesses insights or solutions to circumvent this hurdle and utilize the XHR-fetched images differently, I'd greatly appreciate your input! :)
A heartfelt thank you to the SO community!