http://*.com/questions/6065169/requestanimationframe-with-this-keyword

时间:2023-03-10 04:31:52
http://*.com/questions/6065169/requestanimationframe-with-this-keyword

Observe that you call obj.draw as :

<button onclick="obj.draw()

The first time obj.draw is called, the context is different than when it called by requestAnimationFramemultiple times, as a callback function before the repaint.

So try by saving this in a variable which is outside the scope of the callback function.

Something like :

var obj = {
    //...

    draw: function () {
        var sender = this;
        var draw = function () {
            document.getElementById(sender.id).style.left = (sender.speed++) + 'px';
            window.requestAnimationFrame(draw);
        }
        draw();
    }
}

Here is an updated demo of how this would look like.

http://*.com/questions/6065169/requestanimationframe-with-this-keyword