2014-04-26 20 views
0

有人可以解釋爲什麼這段代碼不起作用嗎?它應該在畫布上畫出兩個划槳和一個球(矩形)。我是JavaScript新手,我正在學習這個YouTube教程,但我幾乎一開始就陷入困境。除了不知道爲什麼它沒有繪製遊戲的所有元素,我也不明白主函數中var = loop函數的含義。請幫助!!JavaScript,不能在乒乓中畫槳和球。有人可以解釋我爲什麼嗎?

var WIDTH=700; 
    var HEIGHT=500; 
    var pi=Math.PI; 

    var canvas; 
    var ctx; 
    var keystate; 

    var player; 
    var ai; 
    var ball; 

    player = { 
     x: null, 
     y: null, 
     width: 20, 
     height: 100, 

     update: function(){}, 
     draw: function(){ 
      ctx.fillRect(this.x, this.y, this.width, this.height); 
      } 
    } 

    ai = { 
     x: null, 
     y: null, 
     width: 20, 
     height: 100, 

     update: function(){}, 
     draw: function(){ 
      ctx.fillRect(this.x, this.y, this.width, this.height); 
      } 
    } 


    ball = { 
     x: null, 
     y: null, 
     side: 20, 

     update: function(){}, 
     draw: function(){ 
      ctx.fillRect(this.x, this.y, this.side, this.side); 
      } 
    } 


    function main(){ 
     canvas = document.createElement("canvas"); 
     canvas.width = WIDTH; 
     canvas.height = HEIGHT; 
     ctx = canvas.getContext("2d"); 
     document.body.appendChild(canvas); 

     init(); 

     var loop = function(){ 
      update(); 
      draw(); 

      window.requestAnimationFrame(loop,canvas); 
     }; 
     window.requestAnimationFrame(loop,canvas); 
    } 

    function init(){ 
     player.x = player.width; 
     player.y = (HEIGHT - player.height)/2; 

     ai.x = WIDTH - (player.width + ai.width); 
     ai.y = (HEIGHT - ai.height)/2; 

     ball.x = (HEIGHT - ball.side)/2; 
     ball.y = (HEIGHT - ball.side)/2; 
    } 

    function update(){ 
     ball.update(); 
     player.update(); 
     ai.update(); 
    } 

    function draw(){ 
     ctx.fillRect(0,0,WIDTH,HEIGHT); 
     ctx.fillStyle = "#fff"; 

     ball.draw(); 
     player.draw(); 
     ai.draw(); 
    } 

    main(); 

</script> 

+0

不知道如果你關心,但有一個錯誤在61行,錯誤是,當你追加'canvas'身體。錯誤說你不能追加null的Child。我可以建議做到以下幾點:'body = document.getElementsByTagName('body')[0]; body.appendChild(canvas);'請確保告訴我,這是否有幫助,或者如果你認爲它是不相關的,因爲希望至少有一個人從中學習。 – Brendan

+0

我做了兩個,你們建議的東西,加上我重寫的主體部分,而不是頭部分的腳本和它的工作。非常感謝你! – user3213733

回答

2

您在白色繪製的一切。 這就是爲什麼你什麼都看不到。背景是白色的,您繪製的形狀也是如此。

嘗試

function draw(){ 
    ctx.fillStyle = "#fff"; 
    ctx.fillRect(0,0,WIDTH,HEIGHT); 

    ctx.save(); 
    ctx.fillStyle = "#000" 
    ball.draw(); 
    player.draw(); 
    ai.draw(); 
    ctx.restore(); 
}