使用EaselJS库在Firefox中运行缓慢

use*_*040 5 javascript canvas easeljs

我想知道为什么这个简单的移动代码在IE和Chrome中运行顺畅,在Firefox中看起来很慢,尽管它保持相同的FPS速率.

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

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();

}
Run Code Online (Sandbox Code Playgroud)

Jac*_*din 1

画布文本渲染速度很慢。<canvas>与将 FPS 写入单独的元素相反,在其中生成文本会对自己造成伤害。

但是,您可以用来加速已编写内容的一项技术是限制某些计算量大的任务(渲染 FPS)不以与最关键任务(球弹跳)相同的频率运行。

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

true这是一个每调用六十次就会返回一次的闭包。

var onceEverySixty = (function(){
    var i = 0;
    return function(){
        i++;
        return ((i % 60) == 0);
    }
})();
Run Code Online (Sandbox Code Playgroud)

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

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