我正在尝试根据对象数组获取不同的图像源。
如果某人是男性,则应显示men.png。
如果一个人是女性,则应该显示female.png。
问题是我在画布中只得到了female.png。
另一个问题是我的回调函数没有按循环变量的顺序调用。
这是代码。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<canvas id ="canvas3" width="1100" height="100" ></canvas>
</div>
<script>
var person = [{name:" Mr.Ram T",gender:"Male"}, {name:" Dr.Shila G", gender:"Female"}, {name: " Dr. J Phil", gender:"Male" } , {name:" Mrs. Sita W",gender:"Female"}, {name:" Mrs. Gita W",gender:"Female"}, {name:" Mrs. Rita W",gender:"Female"}];
function myCallBack(ilocal)
{
return function()
{ alert(ilocal);
ctx.drawImage(img, 10+ilocal*180, 5, 20, 20);
};
}
for (i=0;i<6;i++)
{
var canvas = document.getElementById('canvas3');
var ctx = canvas.getContext('2d');
var img = new Image();
if( person[i].gender == "Male")
{
img.src = "men.png";
}
else
{
img.src = "female.png";
}
if ( img.complete )
{
ctx.drawImage(img, 10+i*180, 5, 20, 20);
}
else
{
img.onload = myCallBack(i);
}
}
</script>
</body>
</html>
答案 0 :(得分:1)
更好的选择是在应用开始之前预先加载您的图片......
以下是在您尝试绘制图片之前如何完全加载这些图片:
src
。onload
回调设置为常用功能(f.ex:myCallback
)
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var urls=[
'https://dl.dropboxusercontent.com/u/139992952/multple/sillouette1.png',
'https://dl.dropboxusercontent.com/u/139992952/multple/sillouetteWoman.png'
];
var images=[];
var loadedCount=urls.length;
for(var i=0;i<urls.length;i++){
var image=new Image();
image.onload=myCallback;
image.src=urls[i];
images.push(image);
}
function myCallback(){
// wait until all images have been fully loaded
if(--loadedCount>0){return;}
// Now all images have been loaded into images[] array
// They are in the same order as the urls[] array
var person = [
{name:" Mr.Ram T",gender:"Male"},
{name:" Dr.Shila G", gender:"Female"},
{name: " Dr. J Phil", gender:"Male" } ,
{name:" Mrs. Sita W",gender:"Female"},
{name:" Mrs. Gita W",gender:"Female"},
{name:" Mrs. Rita W",gender:"Female"}
];
var x=0;
for(var i=0;i<person.length;i++){
var p=person[i];
var genderIndex=(p.gender=='Male')?0:1;
ctx.drawImage(images[genderIndex],x,0);
ctx.fillText(p.name,x,125);
x+=images[genderIndex].width;
}
}
&#13;
body{ background-color:white; }
#canvas{border:1px solid red; margin:0 auto; }
&#13;
<canvas id="canvas" width=600 height=150></canvas>
&#13;