【发布时间】:2015-04-23 08:08:41
【问题描述】:
关于 SO 的第一篇文章,但实际上是我的老用户,因为我在这里找到了我需要的一切……直到现在。
我在使用 XHR 时遇到了一个棘手的问题。我可能会说我是一个 JS 的新手,但我没想到会发生这种事情,我无法绕过......
所以问题是我正在使用“for”循环在远程服务器上检索一堆图像。没问题,它有效。但我想给他们一个 id,以便在他们之后使用他们的“数字”,这样我就可以在画布中使用它们,并为其设置动画。我不知道问题出在哪里,但是 id 的增量出错了。这是我的代码:
<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>
所以你看到有一个按钮,当你点击它时,它会将图像加载到画布上以显示它。
当我想显示 id (console.log(id);) 时,id 在 request.onload 函数中是可以的(我的意思是,它像 1、2、3…)但在函数内部它总是 113。这是我无法理解的事情。我想这是因为 XHR 是异步的,或者类似的东西……这就是我真正的新手……
那么,如果有人有钥匙,或者知道什么可以绕过并以另一种方式使用 XHR 加载的图像,我会很高兴阅读它! :)
非常感谢 SO 社区!
【问题讨论】:
标签: javascript ajax xmlhttprequest blob increment