Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sluggish movement in Firefox using EaselJS library

I would like to know why this simple ball moving code runs smooth in IE and Chrome and in Firefox it appears sluggish, although it maintains the same FPS rate.

What would I have to do to achieve the same smooth movement across all browsers?

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

}
like image 618
user1856040 Avatar asked Nov 12 '22 16:11

user1856040


1 Answers

Canvas text rendering is slow. You are doing yourself a disservice by generating the text within <canvas> as opposed to writing the FPS to a separate element.

But one technique you could use to speed up what already been written is to limit certain computationally-expensive tasks (rendering the FPS) do not run at the same frequency as the most critical tasks (the ball bouncing).

EaselJS does not allow you to designate certain tasks run more frequently. (createjs.Ticker.setFPS is a static function.) So we'll need to create a work-around.

Here's a closure that will return true once every sixty times it is called.

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

Using this closure, we can then implement it in your code to limit how many times the FPS text gets updated:

function tick(){
    if(onceEverySixty()){
        fps=createjs.Ticker.getMeasuredFPS();
        txt_fps.text=Math.round(fps);
    }
    // The ball-drawing code here, outside the conditional
}
like image 146
Jacob Budin Avatar answered Nov 15 '22 06:11

Jacob Budin