Someone
Someone

Reputation: 3568

Slow performance with javascript/html canvas

So, I've created myself a little demo with javascript/html canvas in the context of a gameloop. You can move a small square by pressing the w,a,s,d keys. However, when held down for more than 3 or 4 seconds, the canvas becomes stuttery and the square almost stops moving.

Here's the javascript;

// --------------------------------------------------------------------
// -- MAIN GAME LOOP
// --------------------------------------------------------------------
function gameLoop(){
    update();
    render();
    requestAnimationFrame(gameLoop);
}

function update(){
    processInput();
};
function render(){
    var canvas = document.getElementById('viewport');
    var ctx = canvas.getContext('2d');

    if(upDown){
        rect.top -= rect.speed;
    }else if(downDown){
        rect.top += rect.speed;
    }else if(leftDown){
        rect.left -= rect.speed;
    }else if(rightDown) {
        rect.left += rect.speed;
    }

    ctx.clearRect(0, 0, 1024, 768);
    ctx.beginPath();
    ctx.rect(rect.left, rect.top, 50, 50, true);
    ctx.closePath();
    ctx.fill();
};

var rect = {
    top: 0,
    left: 0,
    speed: 5
};

// --------------------------------------------------------------------
// -- OTHER FUNCTIONS
// --------------------------------------------------------------------
var rightDown = false;
var leftDown = false;
var upDown = false;
var downDown = false;

function processInput(){
    $(document).keydown(function(e){
        console.log(e.keyCode);
        if(e.keyCode == 87){upDown = true;}
        if(e.keyCode == 83){downDown = true;}
        if(e.keyCode == 68){rightDown = true;}
        if(e.keyCode == 65){leftDown = true;}
    }).keyup(function(){
        upDown = false;
        downDown = false;
        rightDown = false;
        leftDown = false;
    })
}

$(document).ready(function(){
    requestAnimationFrame(gameLoop);
});

Anyone got any ideas?

Here's my codepen;

http://codepen.io/anon/pen/wKGJOr

Upvotes: 1

Views: 249

Answers (1)

James Thorpe
James Thorpe

Reputation: 32202

The issue is because you're calling processInput (via update) within your gameloop. This function is attaching new keydown and keyup event handlers every time it is called. It's only necessary to call it once. Remove the call from update, and (for example) call it within the ready function instead:

$(document).ready(function(){
    processInput();
    requestAnimationFrame(gameLoop);
});

By registering more and more event handlers, you're causing a lot more code to run than is necessary, hence the stuttering.

Updated codepen.

Upvotes: 2

Related Questions