使用 SetInterval 在 Javascript Canvas 问题 glitchy/flashing 上刷新游戏

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

需要有关 Canvas 刷新的帮助,非常不稳定和闪烁,我正在使用 setInterval。不知道如何使用请求动画框架,任何帮助都很好

//启动整个游戏

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)
}

该功能是绘图或png图片,设置为以fps的间隔重新加载,设置为30。

从不..永远..使用setInterval做动画!

使用 requestAnimationFrame,因为它与显示速率同步,并确保您对 DOM (canvas) 所做的更改不会移动到显示器,直到显示硬件在帧之间。

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