函数参数在不改变它的情况下自行递增

时间:2017-09-03 10:45:34

标签: javascript html5 html5-canvas

好的,所以我试图在html5画布上移动一个矩形,然后创建了我的函数。它得到一个速度参数,然后递增到位置,就像这样(c是画布'上下文):

this.moveDown = function moveDown(velocity){
    requestAnimationFrame(moveDown);
    c.clearRect(posX, posY, width, height);
    posY += velocity;
    console.log(velocity);
    c.fillRect(posX, posY, width, height);
}

然后我在另一个javascript文件中调用它以使其工作:

var rect1 = new spiel.Rectangle(10,10, 100,100, "#F0F0F0");
rect1.draw();
rect1.moveDown(1);

正如你所看到的,它的速度为1,并且应该(尽我所知)每次迭代移动矩形1个像素,对吧?问题是,当我尝试console.log()速度变量时,这是控制台中每次迭代返回的内容:

The result of the console.log(velocity)

显然,速度变量每次迭代都会增加。是什么造成的?我该如何解决这个问题?另外,在我调用函数的javascript文件中,如果可能是原因,所有内容都包含在window.load函数中

window.onload = function(){

spiel.drawCanvas(800,600, "#FFF000");

var rect1 = new spiel.Rectangle(10,10, 100,100, "#F0F0F0");
rect1.draw();
rect1.moveDown(1);
};

1 个答案:

答案 0 :(得分:3)

requestAnimationFrame将高分辨率计时器值传递给它调用的函数。这是您在velocity中看到的内容,因为您已将moveDown传递给rAF:

requestAnimationFrame(moveDown);

因此,您首先看到的是用它来调用它,但随后您会看到rAF调用它的计时器值。

(旁注:你无条件地打电话给rAF来安排回调;大概你在某处有停止条件?)

如果您希望它继续获得1,只需使用包装函数或bind

打包机:

this.moveDown = function moveDown(velocity){
    // NOTE: This works because `moveDown` doesn't use `this`
    // If you need `this`, you'd have to do one of the many things to ensure it
    requestAnimationFrame(function() { // Presumably you'll have a stop condition on this?
        moveDown(velocity);
    });
    c.clearRect(posX, posY, width, height);
    posY += velocity;
    console.log(velocity);
    c.fillRect(posX, posY, width, height);
}

bind

this.moveDown = function moveDown(velocity){
    // Handles `this`, in case the function ever changes to use it
    requestAnimationFrame(this.moveDown.bind(this, 1)); // Presumably you'll have a stop condition on this?
    c.clearRect(posX, posY, width, height);
    posY += velocity;
    console.log(velocity);
    c.fillRect(posX, posY, width, height);
}

由于rAF回调可以运行60次/秒,我们可能希望避免每次创建一个函数,所以:

this.moveDown = function moveDown(velocity){
    var handleMove = function() {
        requestAnimationFrame(handleMove); // Presumably you'll have a stop condition on this?
        c.clearRect(posX, posY, width, height);
        posY += velocity;
        console.log(velocity); // And probably remove this
        c.fillRect(posX, posY, width, height);
    }.bind(this); // *IF* you need `this`
    handleMove();
}