将多个图像加载到多个画布中 [英] Loading multiple images into multiple canvases
问题描述
我有一个代码将图像加载到画布上,它工作正常,但当我尝试迭代做多次,它只加载一个图像(最后一个)。任何人都知道为什么?
I got a code for loading an image into a canvas, and it works fine, but when I try to iterate to do it multiple times, it only loads one image (the last one). Anyone knows why?
<pre id="output_1"></pre>
<canvas id="canvas_1"></canvas>
<pre id="output_2"></pre>
<canvas id="canvas_2"></canvas>
<script type="text/javascript">
var pics = [ 'Desert.jpg', 'Hydrangeas.jpg' ];
for(var i=0; i < pics.length; i++) {
var img = new Image();
var ctx = $( '#canvas_'+(i+1) )[0].getContext('2d');
img.onload = function() {
ctx.drawImage(img, 0, 0);
};
img.src = pics[i];
}
</script>
推荐答案
var img
正在循环时被覆盖。在当前执行完成之前,不会调用
onload
。到那时img将等于第三次迭代。
The var img
is being overwritten as you loop. The onload
s will not be called until the current execution is complete. By that time img will equal the 3rd iteration.
修复
var pics = [ 'Desert.jpg', 'Hydrangeas.jpg' ];
function loadImage(i){
var img = new Image();
var ctx = $( '#canvas_'+(i+1) )[0].getContext('2d');
img.onload = function() {
ctx.drawImage(img, 0, 0);
};
img.src = pics[i];
}
for(var i=0; i < pics.length; i++) {
loadImage(i);
}
调用 loadImage
每次调用时都会创建一个对所有变量的新引用。它不同于 onload
,因为它被立即调用,而 onload
是一个回调,必须等待,直到当前执行的上下文完全退出(换句话说,返回,直到没有更多的回报),然后只有那时可以上载发生。
The call to the function loadImage
creates a new reference to all the variable each time it is called. It differs from onload
because it is called immediately, while onload
is a callback and must wait until the currently executing context has completely exited (in other words returned until there are no more returns), then and only then can the onload happen.
这篇关于将多个图像加载到多个画布中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!