设置for循环的限制条件

时间:2012-03-17 21:28:53

标签: javascript for-loop

我的for循环有问题,我确定这是一个简单的我缺少的东西,但是,我试图让三个加载的图像向下移动10个增量,然后停止(三个图像停在10递增。 当我运行代码时,它会运行,但它会在页面上运行(不会在10处停止)。有谁能看到这个问题? 任何帮助都会很棒!

window.addEventListener('load', eventWindowLoaded, false);

function eventWindowLoaded()
{
    canvasApp();
}


function canvasSupport () 
{
    return Modernizr.canvas;
}

function canvasApp()
{
    if (!canvasSupport()) 
    {
        return;
}

    else
{
    theCanvas = document.getElementById("canvas");
    var context = theCanvas.getContext("2d");
}

var toes = new Image();
toes.addEventListener('load', eventShipLoaded , false);
toes.src = "images/toes.png";
var larry = new Image();
larry.addEventListener('load', eventShipLoaded , false);
larry.src = "images/larry.png";
var barry = new Image();
barry.addEventListener('load', eventShipLoaded , false);
barry.src = "images/barry.png";

function eventShipLoaded()
{
    startUp();
}

y=0;

function drawScreen()
{

    for (x = 0; x < 1; x++)
    {
            context.fillStyle = "#aaaaaa";
            context.fillRect(0,0,500,500);
            context.drawImage(toes,0,y,114,339);
            context.drawImage(larry,110,(y+81),86,258);
            context.drawImage(barry,203,(y+72),98,265);
            y+=1;
    }
}


function startUp() 
{
    setInterval(drawScreen,5);
}
}

2 个答案:

答案 0 :(得分:0)

您需要限制y的值。你只有

  y+=1;

答案 1 :(得分:0)

您正在使用“setInterval”而不会取消定时器。这就是图像不断移动的原因。因此,只需计算“drawScreen”被调用的次数,并在第10次调用后停止计时器:

var movements = 0;
var timer = null;

function drawScreen() {
    // ... original code ...

    if (timer && ++movements == 10) {
        clearInterval(timer);
    }
}

function startup() {
    timer = setInterval(drawScreen, 5);
}