【问题标题】:Sluggish movement in Firefox using EaselJS library使用 EaselJS 库在 Firefox 中移动缓慢
【发布时间】:2014-02-19 21:53:47
【问题描述】:

我想知道为什么这个简单的球移动代码在 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();

}

【问题讨论】:

    标签: javascript canvas easeljs


    【解决方案1】:

    Canvas text rendering is slow.&lt;canvas&gt; 中生成文本而不是将 FPS 写入单独的元素,这是对自己的伤害。

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

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

    这是一个闭包,每调用 60 次就会返回一次 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
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-29
      • 2011-09-13
      • 1970-01-01
      • 2013-06-19
      • 1970-01-01
      • 2014-08-21
      • 1970-01-01
      • 2016-11-08
      • 1970-01-01
      相关资源
      最近更新 更多