window.requestAnimationFrame使用object和this关键字

时间:2013-06-30 06:16:57

标签: javascript animation this game-engine requestanimationframe

我正在学习使用javascript的物理引擎的基础知识,并希望将所有引擎和游戏数据保存在一个对象中,但在递归调用draw函数进行动画处理时无法使用'this'关键字现场。我可以成功调用有效的单独绘制函数,但实现多个对象动画不会那么容易

这是一个带有工作测试平台的简单codepen

这是页面

<!doctype html>
<html>

<head>

<style type="text/css">

    #obj{
        width: 50px;
        height: 200px;
        background: red;
        position: absolute;
        left: 100px;
        bottom: 200px;
    }

    #ground{
        width: 100%;
        height: 200px;
        background: #222;
        position: absolute;
        bottom: 0;
        left: 0;
    }

</style>


</head> 

<body>

<div id="content">

<section>
    <button onclick="draw()">draw()</button><br>
    <button onclick="obj.draw()">obj.draw()</button>
</section>

<article>

    <div id="obj"></div>
    <div id="ground"></div>

</article>  

</div> <!-- END CONTENT -->

</body>

<script type="text/javascript">

var obj = {
    // variables
    id: 'obj',
    width: 50,
    height: 200,
    angle: 30,
    speed: 20,
    acceleration: 4/60,
    deceleration: 2/60,
    moving: false,
    jumping: false,
    // Get methods
    x: function(){return parseInt(window.getComputedStyle(document.getElementById(this.id)).left)},
    y: function(){return parseInt(window.getComputedStyle(document.getElementById(this.id)).bottom)},
    // engine methods
    scale_x: function(){return Math.cos((this.angle * Math.PI) / 180)},
    scale_y: function(){return Math.sin((this.angle * Math.PI) / 180)},
    velocity_x: function(){return this.speed * this.scale_x()},
    velocity_y: function(){return this.speed * this.scale_y()},
    cx: function(){return this.x() + this.width},
    cy: function(){return this.y() + this.height},
    // set methods
    setAngle: function(val){this.angle = val},
    setAcceleration: function(val){this.acceleration = val / 60},
    setDeceleration: function(val){this.deceleration = val / 60},
    setSpeed: function(val){this.speed = val},
    setMoving: function(val){this.moving = val},
    setJumping: function(val){this.jumping = val},
    draw: function(){
        document.getElementById(this.id).style.left = (this.speed++) + 'px';
        window.requestAnimationFrame(this.draw);
    }
}

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

</script>   

</html> 

感谢您的帮助,

安德鲁

1 个答案:

答案 0 :(得分:1)

请注意您将obj.draw称为:

<button onclick="obj.draw()

第一次调用obj.draw时,上下文与多次调用requestAnimationFrame时的上下文不同,作为重绘前的回调函数。

因此,请尝试将保存在回调函数范围之外的变量中。

类似的东西:

var obj = {    
    //...

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

以下是updated demo的结果。