2013-06-23 142 views
3

我以等距遊戲開始,當畫出地面的所有部分時,畫布閃爍(不在IE中)。當我將fps設置爲20或更少時,閃爍停止。我該如何解決這個問題?有任何想法嗎?HTML5 Canvas在繪圖上閃爍

var camerax = 300, cameray = 100; 
var fps = 60; 

function draw() { 
    clearCanvas(); 
    drawGround(); 
} 

function drawGround() { 
    var img = new Image(); 
    img.onload = function() { 
    var width = img.width; 
    var height = img.height; 
    for (var x = 0; x < 3; x++) { 
     for (var y = 3; y >= 0; y--) { 
       mx = (x-y)*height + camerax; 
       my = (x+y)*height/2 + cameray; 
       ctx.drawImage(img, mx, my); 
      } 
     } 
    } 
    img.src = "ground.png"; 
} 

var loop = setInterval(function() { 
    update(); 
    draw(); 
}, 1000/fps); 

回答

4

現在你重裝每幀的圖像,除非該幀的16毫秒內onload回調火災,你會看到一個空白的畫布。

您只需要撥打new Image,img.onload序列一次,以預載圖像。然後,onload回調將啓動您的第一幀,並且繪製調用可以自由地在內存中使用該圖像。

喜歡的東西:

var camerax = 300, cameray = 100; 
var fps = 60; 
var img; 
var loop; 

function init() { 
    img = new Image(); 
    img.onload = function() { 
     loop = setInterval(function() { 
      update(); 
      draw(); 
     }, 1000/fps); 
    }; 
    img.src = "ground.png"; 
} 

function draw() { 
    clearCanvas(); 
    drawGround(); 
} 

function drawGround() { 
    var width = img.width; 
    var height = img.height; 
    for (var x = 0; x < 3; x++) { 
     for (var y = 3; y >= 0; y--) { 
       mx = (x-y)*height + camerax; 
       my = (x+y)*height/2 + cameray; 
       ctx.drawImage(img, mx, my); 
      } 
     } 
    } 
} 

當然,它變得更加複雜,一旦你等待多個圖像預加載,因爲你需要啓動循環只是其中一次全部完成。

0

不錯的提示,freejosh!謝謝!我的屏幕現在不閃爍,代碼結果如下:

 var canvas = document.getElementById("game"); 
     var ctx = canvas.getContext("2d"); 

     var camerax = 300, cameray = 100; 
     var fps = 60; 
     var img; 
     var loop; 

     function update() { 
     } 

     function draw() { 
      clearCanvas(); 
      drawGround(); 
     } 

     function clearCanvas() { 
      ctx.clearRect(0, 0, canvas.width, canvas.height); 
     } 

     function drawGround() { 
      var width = img.width; 
      var height = img.height; 
      for (var x = 0; x < 3; x++) { 
       for (var y = 3; y >= 0; y--) { 
        mx = (x-y)*height + camerax; 
        my = (x+y)*height/2 + cameray; 
        ctx.drawImage(img, mx, my); 
       } 
      } 
     } 

     function init() { 
      img = new Image(); 
      img.onload = function() { 
       drawGround(); 
      }; 
      img.src = "ground.png"; 
     } 

     function keyListener(e){ 
      e = e || window.event 

      if(e.keyCode==37){ 
       camerax--; 
      } 
      else if(e.keyCode==39){ 
       camerax++; 
      } 
      else if(e.keyCode==38){ 
       cameray--; 
      } 
      else if(e.keyCode==40){ 
       cameray++; 
      }       
     } 

     window.onkeypress = function(e) { 
      keyListener(e); 
     } 

     init(); 
     var loop = setInterval(function() { 
      update(); 
      draw(); 
     }, 1000/fps);