Javascript Canvas上的游戏刷新使用SetInterval发出故障/闪烁

时间:2017-11-09 23:03:09

标签: javascript canvas setinterval requestanimationframe game-loop

需要帮助Canvas刷新,非常小故障和闪烁,以及我使用setInterval。不知道如何使用requestanimation框架,任何帮助都很棒

//启动整个游戏

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的间隔设置为reod,设置为30。

1 个答案:

答案 0 :(得分:1)

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

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

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