我正在尝试使用此代码,但是当我在浏览器(新Chrome)中测试时,move_1_3功能首先发生,然后move_1_2,请问如何纠正它? (在代码中我想改变3张图片的位置)
window.onload = main;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
function main(){
backGround.src = "http://www.ednetti.hu/images/cj0n9l0o6m.jpg";
backGround.onload = function(){
context.drawImage(backGround, 0, 0, w, h);
ballImg.src = "http://www.clipartsfree.net/vector/large/SABROG_Glass_Blue_Ball_Vector_Clipart.png";
ballImg.onload = function (){
cupImg.src = "http://www.clker.com/cliparts/8/m/s/0/t/K/blue-cup-hi.png";
cupImg.onload = function(){
timer = setInterval(move_1_2, timeStep);
timer = setInterval(move_1_3, timeStep);
//time3 = setInterval(move_2_3, timeStep);
};
};
};
}
function move_1_2 () {
if (steps >2){
return;
}
posX =((posX2-posX1)/density)*i;
bposX =(bposX2-bposX1)/density*i;
context.clearRect(0, 0, w, h);
context.drawImage(backGround, 0, 0, w, h);
if(ballPos == 1){
context.drawImage(ballImg, bposX1 + bposX, bposY, ballw, ballh);
}
else if(ballPos == 2){
context.drawImage(ballImg, bposX2 - bposX, bposY, ballw, ballh);
}
else if(ballPos == 3){
context.drawImage(ballImg, bposX3, bposY, ballw, ballh);
}
context.drawImage(cupImg, posX1 + posX, posY, cupw, cuph);
context.drawImage(cupImg, posX3, posY, cupw, cuph);
context.drawImage(cupImg, posX2 - posX, posY, cupw, cuph);
i++;
if (i == density){
i = 0;
steps ++;
switch (ballPos){
case 1:
ballPos = 2;
break;
case 2:
ballPos = 1;
break;
}
clearInterval(timer);
}
}
function move_1_3 () {
if (steps >2){
return;
}
posX =((posX3-posX1)/density)*i;
bposX =(bposX3-bposX1)/density*i;
context.clearRect(0, 0, w, h);
context.drawImage(backGround, 0, 0, w, h);
if(ballPos == 1){
context.drawImage(ballImg, bposX1 + bposX, bposY, ballw, ballh);
}
else if(ballPos == 3){
context.drawImage(ballImg, bposX3 - bposX, bposY, ballw, ballh);
}
else if(ballPos == 2){
context.drawImage(ballImg, bposX2, bposY, ballw, ballh);
}
context.drawImage(cupImg, posX1 + posX, posY, cupw, cuph);
context.drawImage(cupImg, posX2, posY, cupw, cuph);
context.drawImage(cupImg, posX3 - posX, posY, cupw, cuph);
i++;
if (i == density){
steps ++;
switch(ballPos){
case 1:
ballPos = 3;
break;
case 3:
ballPos = 1;
break;
case 2:
ballPos = 2;
break;
}
clearInterval(timer);
i = 0;
}
}
答案 0 :(得分:2)
一种解决方案是将行timer = setInterval(move_1_3, timeStep);
移到函数move_1_2
内部,位于该函数的最末端之前。
如果由于函数重用而无效,您仍然可以使用带有匿名函数的单个setInterval
来运行一个函数:
cupImg.onload = function(){
timer = setInterval(function() {
move_1_2();
move_1_3();
// move_2_3();
}, timeStep);
};
答案 1 :(得分:0)
问题在于setInterval函数调用的机制
您可以在此处找到更多信息settimeout-setinterval
最小延迟
计时器分辨率有限。实际上,最小的计时器滴答 对于现代浏览器,在1ms和15ms之间变化,并且可以更大 旧的。
如果计时器分辨率为10,则两者之间没有区别 setTimeout(..,1)和setTimeout(..,9)。
您同时启动了2个功能。你不确定谁将是第一个。 尝试使用这样的东西:
timer = setInterval(function(){move_1_2(); setInterval(move_1_3, timeStep);}, timeStep);
或尝试使用延迟。