2015-12-21 25 views
0

我想爲自上而下的射手實現滾動效果。現在我有一羣我正在畫屏幕的星星。我怎樣才能使它看起來好像玩家前進這是我到目前爲止執行(向下滾動星):JavaScript - 滾動像素數組

var canvas = document.getElementById('canvas'), 
    context = canvas.getContext('2d'), 
    stars; 

function render() { 
    requestAnimationFrame(render); 

    context.fillStyle = 'black'; 
    context.fillRect(0, 0, canvas.width, canvas.height); 
    context.fillStyle = 'white'; 
    for(var y = 0; y < canvas.height; y++) { 
     for(var x = 0; x < canvas.width; x++) { 
      if(stars[y][x]) { 
       context.fillRect(x, y, 1, 1); 
      } 
     } 
    } 
} 

function update() { 
    // TODO: game logic 
} 

window.onresize = function() { 
    canvas.width = window.innerWidth; 
    canvas.height = window.innerHeight; 
    canvas.style.width = canvas.width + 'px'; 
    canvas.style.height = canvas.height + 'px'; 

    stars = new Array(canvas.height); 
    for(var y = 0; y < canvas.height; y++) { 
     stars[y] = new Array(canvas.width); 

     for(var x = 0; x < canvas.width; x++) { 
      if(Math.floor(Math.random() * 1000) == 0) { 
       stars[y][x] = true; 
      } else { 
       stars[y][x] = false; 
      } 
     } 
    } 
} 

window.onresize(); 
setInterval(update, 1000/60); 
requestAnimationFrame(render); 
+0

例如:http://www.kevs3d.co.uk/dev/warpfield/ – markE

回答

0

這個怎麼樣?

function render() { 
    requestAnimationFrame(render); 

    stars.unshift(stars.pop()); // added 

    context.fillStyle = 'black'; 
    context.fillRect(0, 0, canvas.width, canvas.height); 
    context.fillStyle = 'white'; 
    for(var y = 0; y < canvas.height; y++) { 
     for(var x = 0; x < canvas.width; x++) { 
      if(stars[y][x]) { 
       context.fillRect(x, y, 1, 1); 
      } 
     } 
    } 
} 

此代碼將底部像素移動到頂部,並讓其他像素每幀向下滑動。