我有以下代码,假设要执行以下操作:
出于某种原因,它只在第二个画布的末尾加载一个图像。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var boxImages = ['img/white.jpg', 'img/blue.jpg', 'img/black.jpg', 'img/brown.jpg', 'img/green.jpg', 'img/red.jpg'];
var IMAGE_WIDTH=50;
var MAX_COLS = 7;
var MAX_ROWS = 8;
var numberOfSteps = 2;
var allSteps = [];
allSteps[0] = '0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2';
allSteps[1] = '0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 3';
$('#result_div').html('<p>All Steps : ' + allSteps + '</p>');
for (count=0; count < numberOfSteps; count++)
{
$('#result_div').append('<h3>Step : ' + count + '</h3>');
$('#result_div').append('<p><canvas id="resultCanvas' + count + '" width="350" height="400" style="border:1px solid #c3c3c3;" ></p>');
resultCanvas=document.getElementById('resultCanvas'+count);
resultCtx = resultCanvas.getContext("2d");
currentSolution = allSteps[count].split(" ");
for (r=0; r < MAX_ROWS; r++)
{
for (c=0; c < MAX_COLS; c++)
{
imgNumber=currentSolution[((r)*MAX_COLS)+c];
if (imgNumber != 0)
{
boxX = (c*IMAGE_WIDTH);
boxY = (r*IMAGE_WIDTH);
cimg=new Image();
cimg.onload = function(){resultCtx.drawImage(cimg,boxX,boxY);};
cimg.src=boxImages[imgNumber];
}
}
}
}
});
</script>
<body>
<div id="result_div"></div>
</script>
</body>
</html>
答案 0 :(得分:1)
我还没有对此进行过测试,但我猜你会比实际加载的图片更快地覆盖你的cimg.src
和cimg.onload
。您是否尝试过使用图像数组?
var cimgs = [];
var IMAGE_WIDTH=50;
/*
...
*/
if (imgNumber != 0)
{
boxX = (c*IMAGE_WIDTH);
boxY = (r*IMAGE_WIDTH);
cimgs.push(new Image());
cimgs[cimgs.length - 1].onload = (function(img,x,y){
return function(){resultCtx.drawImage(img,x,y);};
})(cimgs[cimgs.lenght - 1],boxX,boxY);
cimgs[cimgs.length - 1].src = boxImages[imgNumber];
}
}