Devan
Devan

Reputation: 3

Game Refresh on Javascript Canvas Issue glitchy/flashing, using SetInterval

Need help with Canvas refresh, very glitchy and flashing, and im using setInterval. Dont know how to use requestanimation frame, any help is great

//initiates entire game

function fullLoader() {     

    setInterval(drawPoke, fps);
    setInterval(drawHaunt, fps);
    setInterval(drawChar, fps);
    setInterval(drawDusk, fps);
    setInterval(refresh, 1000/30);
}

function refresh() {

    con.clearRect(0, 0, canvas.width, canvas.height)
}

The function are drawings or png images and are set to relaod at the interval of fps which is set to 30.

Upvotes: 0

Views: 96

Answers (1)

Blindman67
Blindman67

Reputation: 54026

Never..ever.. use setInterval for animation!

Use requestAnimationFrame as it is synced to the display rate and ensures that changes you make to the DOM (canvas) do not get moved to the display until the display hardware is in between frames.

function fullLoader() {     
    requestAnimationFrame(mainLoop); // get first frame
}

// This mainLoop is called every 1/60th second (if you return in under 1/60th second
// if the render time is loonger than 1/60 then you will have to use
// time to keep the speed at 1/30th second. Search SO for how.
function mainLoop(time){  // time is given by browser, in ms 1/1000 
                          // accurate to 1/1,000,000
    refresh();
    drawPoke();
    drawHaunt();
    drawChar()
    drawDusk();
    requestAnimationFrame(mainLoop); // get next frame
}

function refresh() {
    con.clearRect(0, 0, canvas.width, canvas.height);
}

Upvotes: 1

Related Questions