使用EaselJS库在Firefox中运行缓慢

时间:2012-11-27 09:54:56

标签: javascript canvas easeljs

我想知道为什么这个简单的移动代码在IE和Chrome中运行顺畅 虽然它保持相同的FPS率,但在Firefox中看起来很迟钝。

要在所有浏览器中实现相同的平滑移动,我需要做些什么?

var canvas,canvasContext,
    ball,txt_shadow,txt_fps,
    speed,angle;        

function init() {

    canvas = document.getElementById("canvas");
    canvasContext = canvas.getContext("2d");
    canvas.width=window.innerWidth;
    canvas.height=window.innerHeight;

    stage = new createjs.Stage(canvas);
    stage.autoClear = true;

    txt_shadow= new createjs.Shadow("black", 1, 1, 0);

    ball = new createjs.Shape();
    ball.graphics.beginFill("red").drawCircle(0, 0, 40);

    txt_fps = new createjs.Text("", "18px Arial", "white");
    txt_fps.shadow=txt_shadow;
    txt_fps.x=canvas.width/2;txt_fps.y=100;

    stage.addChild(txt_fps,ball);

    ball.x=canvas.width/2;ball.y=canvas.height/2;
    angle=Math.random()*360;
    speed=8;

    createjs.Ticker.addListener(window);
    createjs.Ticker.setFPS(60);

} 

function tick() {    

    fps=createjs.Ticker.getMeasuredFPS();
    txt_fps.text=Math.round(fps);    
    ball.x += Math.sin(angle*(Math.PI/-180))*speed;
    ball.y += Math.cos(angle*(Math.PI/-180))*speed;

    if (ball.y<0 || ball.x<0 || ball.x>canvas.width || ball.y>canvas.height) {
        angle+=45;
    }
    stage.update();

}

1 个答案:

答案 0 :(得分:1)

Canvas text rendering is slow.通过在<canvas>内生成文本而不是将FPS写入单独的元素,您自己是一种伤害。

但是,你可以用来加速已经编写的一种技术是限制某些计算成本高昂的任务(渲染FPS)与最关键任务(球弹跳)的频率不同。

EaselJS不允许您指定更频繁运行的某些任务。 (createjs.Ticker.setFPS是一个静态函数。)所以我们需要创建一个解决方法。

这是一个闭包,每隔六十次就会返回true一次。

var onceEverySixty = (function(){
    var i = 0;
    return function(){
        i++;
        return ((i % 60) == 0);
    }
})();

使用此闭包,我们可以在您的代码中实现它,以限制FPS文本更新的次数:

function tick(){
    if(onceEverySixty()){
        fps=createjs.Ticker.getMeasuredFPS();
        txt_fps.text=Math.round(fps);
    }
    // The ball-drawing code here, outside the conditional
}