2014-09-19 201 views
0

在畫布中,有一個圖像,它在箭頭鍵的事件上移動。 但它在Firefox中閃爍,並在Chrome和IE上正常工作。HTML5畫布圖像移動閃爍

我不想要一個解決方案,只清除畫布的一部分,因爲我還在畫布上添加了其他東西。

下面是我的代碼:

var 
velY = 0, 
velX = 0, 
speed = 2, 
friction = 0.90, 
keys = [], 

canvas = document.getElementById("canvas"), 
ctx = canvas.getContext("2d"), 
playerDirection="img/player/player_back.png"; 

function update() { 

    if (keys[38]) { 
     if (velY > -speed) { 
      velY--; 
      playerDirection="img/player/player_back.png"; 
     } 
    } 

    if (keys[40]) { 
     if (velY < speed) { 
      velY++; 
      playerDirection="img/player/player_front.png"; 
     } 
    } 
    if (keys[39]) { 
     if (velX < speed) { 
      velX++; 
      playerDirection="img/player/player_right.png"; 
     } 
    } 
    if (keys[37]) { 
     if (velX > -speed) { 
      velX--; 
      playerDirection="img/player/player_left.png"; 
     } 
    } 

    velY *= friction; 
    y += velY; 
    velX *= friction; 
    x += velX; 

    if (x >= canvas.width - player.width) { 
     x = canvas.width - player.width; 
    } else if (x <= 5) { 
     x = 5; 
    } 

    if (y > canvas.height - player.height) { 
     y = canvas.height - player.height; 
    } else if (y <= 5) { 
     y = 5; 
    } 

    ctx.clearRect(0, 0, canvas.width, canvas.height); 
    playerObj = new Image(); 
    playerObj.onload = function() 
    { 
     ctx.drawImage(playerObj, x, y); 
    }; 
    playerObj.src = playerDirection; 


} 

update(); 


function handlerKeyDown(e) 
{ 
    keys[e.keyCode] = true; 
} 

function handlerKeyUp(e) { 
    keys[e.keyCode] = false; 
} 

感謝adavance。

+0

您每次更新都會加載圖像?你爲什麼不緩存它們?這可能有幫助。 – MaxArt 2014-09-19 09:53:33

+0

我想通了,在Firefox的畫布圖像不要從緩存中加載。任何想法如何從緩存加載圖像? – 2014-09-19 09:54:54

+0

不,你不能真正控制從Javascript。 *但是*您可以將'Image'對象存儲在一個數組中。 – MaxArt 2014-09-19 09:59:17

回答

1

這就是我的意思與「緩存圖像」:

var images = {}; // This will contain the Image objects 
// Other definitions... 

function update() { 

    if (keys[38]) { 
     if (!images.back) { 
      // The image object hasn't been defined yet. 
      images.back = new Image(); 
      images.back.src = "img/player/player_back.png"; 
     } 
     playerObj = images.back; 
    } 
    // Other checks on the pressed keys 
    // ... 

    // Computations on the position... 

    if (!playerObj.naturalWidth) { 
     // If naturalWidth/Height is 0, then the image hasn't been loaded yet. 
     // We update the onload listener to draw in the right position. 
     playerObj.onload = function() { 
      ctx.drawImage(playerObj, x, y); 
     }; 
    // The image has already been loaded, so we just draw it 
    } else ctx.drawImage(playerObj, x, y); 
} 

(如在你的代碼的警告,似乎要處理多個按鍵,但最後一個序列起來向下 - 右 - 左總是「勝過」其他人。是否真的是你想要的?)