2015-10-20 201 views
-4

似乎有像这样的其他问题,我想避免缓冲区和/或requestAnimationFrame()。Javascript画布闪烁

在最近的一个项目中,玩家闪烁但我找不到原因。你可以找到的jsfiddle项目:https://jsfiddle.net/90wjetLa/

function gameEngine() { 
    timer += 1; 
    timer = Math.round(timer); 
    // NEWSHOOT? 
    player.canShoot -= 1; 
    // MOVE: 
    movePlayer(); 
    shootEngine(); // Schussbewegung & Treffer-Abfrage 

    // DRAW: 
    ctx.beginPath(); 

    canvas.width = canvas.width; 
    ctx.beginPath(); 

    ctx.fillStyle = 'black'; 
    ctx.rect(0, 0, canvas.width, canvas.height); 
    ctx.fill(); 
    drawField(); 
    drawPlayer(); 

    drawShoots(); 

    setTimeout(gameEngine, 1000/30); 
} 
+0

JavaScript中没有'const'。 – klenium

+0

看看Mozilla开发者https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/const? – user2531284

+0

@ user2531284这就是es6。没有在每个浏览器中实现,还有一个大的警告... – Michelangelo

回答

0

每次写一个可见的画布时,浏览器想的更新显示。您的绘图例程可能与浏览器显示更新不同步。​​函数允许您在显示刷新之前运行所有绘图程序。您的其他朋友正在使用不可见的缓冲区画布。将所有内容绘制到缓冲区画布上,然后将缓冲区绘制到可见画布上。 gameEngine函数应该只能每帧运行一次,如果运行多次,您可能会看到闪烁。尝试以下操作以清除同一帧中的多个运行。

(编辑):您可能还想清除画布而不是设置宽度。

(edit2):您可以将clearRect,rectfill组合为一个命令ctx.fillRect(0, 0, canvas.width, canvas.height);

var gameEngineTimeout = null; 
function gameEngine() { 
    // clear pending gameEngine timeout if it exists. 
    clearTimeout(gameEngineTimeout); 
    timer += 1; 
    timer = Math.round(timer); 
    // NEWSHOOT? 
    player.canShoot -= 1; 
    // MOVE: 
    movePlayer(); 
    shootEngine(); // Schussbewegung & Treffer-Abfrage 

    // DRAW: 
    ctx.beginPath(); 

    //canvas.width = canvas.width; 
    //ctx.clearRect(0, 0, canvas.width, canvas.height); 
    //ctx.beginPath(); 

    ctx.fillStyle = 'black'; 
    ctx.fillRect(0, 0, canvas.width, canvas.height); 
    //ctx.fill(); 
    drawField(); 
    drawPlayer(); 

    drawShoots(); 

    gameEngineTimeout = setTimeout(gameEngine, 1000/30); 
}