HTML5 - 多个动画,不同的fps

时间:2014-07-18 18:55:29

标签: html5 requestanimationframe

我想创建一个包含多个精灵的html5游戏。

对于不同的元素,我想创建一个固定的fps。

例如:

步行 - 10 fps,因此将在1秒内显示10个精灵

运行 - 15 fps

攻击 - 3 fps

如何使用requestAnimationFrame创建它,而不是使用set timeout或setinterval。

1 个答案:

答案 0 :(得分:0)

您可以使用requestAnimationFrame的时间戳功能以不同的每秒帧数触发动画

function animate(timestamp){
    // timestamp is a representation of the current elapsed time
}

该方法是在您希望执行每个操作时设置个别时间:

WalkTriggerTime = timest + 1000/desiredFPS;

然后在requestAnimationFrame时间戳超过此触发时间时执行操作

if( timestamp > WalkTriggerTime ){ 

    // execute a walk 

    // and reset the trigger timer

    WalkTriggerTime = timest + 1000/desiredFPS;
}

示例代码和演示:http://jsfiddle.net/m1erickson/D6SU8/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var animations=[]
    var fps03={x:20,y:20,fps:03,frameCount:0,triggerTime:null,}
    var fps10={x:20,y:40,fps:10,frameCount:0,triggerTime:null,}
    var fps15={x:20,y:60,fps:15,frameCount:0,triggerTime:null,}
    var stopAnimation=false;
    animations.push(fps03,fps10,fps15);

    for(var i=0;i<animations.length;i++){
        var a=animations[i];
        ctx.fillText(a.fps,a.x,a.y)
    }

    requestAnimationFrame(animate);

    function animate(t){

        if(!stopAnimation){requestAnimationFrame(animate);}

        for(var i=0;i<animations.length;i++){
            var a=animations[i];
            if(!a.triggerTime){a.triggerTime=t+1000/a.fps;}
            if(t>a.triggerTime){
                a.triggerTime=t+1000/a.fps;
                a.frameCount++;
                ctx.clearRect(a.x+20,a.y-15,19,20)
                ctx.fillText(a.frameCount,a.x+20,a.y)
                ctx.fillRect(a.x+40,a.y-10,a.frameCount,15);
                if(a.x+40+a.frameCount>canvas.width-20){stopAnimation=true;}
            }
        }
    }

}); // end $(function(){});
</script>
</head>
<body>
    <h4>Using the timestamp feature of RAF to control fps</h4>
    <h4>Left#:fps, Mid#:Execution Count</h4>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>