2016-05-13 78 views
2

我正在構建我的第一個迷你JS遊戲,並通過w3schools教程工作,但無法在codepen預覽區域加載我的第一個組件。這是一個非常令人失望的前幾步。我知道myGameArea加載正常,因爲它的風格流行,但我只想要一個簡單的紅色方塊來繪製它的頂部。如何用Javascript繪製畫布

var myGamePiece; 

function startGame() { 
    myGamePiece = new component(30, 30, "red", 10, 120); 
    myGameArea.start(); 
} 

var myGameArea = { 
    canvas: document.createElement("canvas"), 
    start: function() { 
    this.canvas.width = 480; 
    this.canvas.height = 270; 
    this.context = this.canvas.getContext("2d"); 
    document.body.insertBefore(this.canvas, document.body.childNodes[0]); 
    this.interval = setInterval(updateGameArea, 20); 
    }, 
    clear: function(){ 
    this.context.clearRect(0,0, this.canvas.width, this.canvas.height); 
    } 
} 


function component(width, height, color, x, y) { 
    this.width = width; 
    this.height = height; 
    this.x = x; 
    this.y = y;  
    this.update = function(){ 
     ctx = myGameArea.context; 
     ctx.fillStyle = color; 
     ctx.fillRect(this.x, this.y, this.width, this.height); 
    } 
} 

function updateGameArea() { 
    myGameArea.clear(); 
    myGameArea.update(); 
} 

<button onClick="startGame()"> 
Press 
</button> 
+0

您是否在控制檯中發現任何錯誤? – dan08

+0

你似乎沒有定義'myGameArea.update()' –

+0

你的意思是'myGamePiece.update()'? –

回答

2

updateGameArea電話myGameArea.clear(),然後試圖調用update不存在。運行時沒有出現錯誤?您可能需要撥打myGamePiece.update()