簡體   English   中英

畫布顯示的是單個對象,而不是多個

[英]Canvas is displaying a single object instead of multiple

我已經為彈跳球創建了腳本,並且我想嘗試添加另一個球以使其更加有趣。 但是該代碼似乎不起作用,並且在我嘗試做的時候又添加了一個球。 我想使用相同的功能來執行此操作,因為它更緊湊,更靈活。

 function startGame() { GameArea.start(); Ball = new CircComp('red' , window.innerWidth/ 2 , window.innerHeight / 2.5 ); Ball.yAngle = 10; Ball.xAngle = 10; Ball.radius = 20; Ball1 = new CircComp('green' , window.innerWidth/ 2 , window.innerHeight / 2.5 ); Ball1.yAngle = -10; Ball1.xAngle = -10; Ball1.radius = 20; } var GameArea = { canvas : canvas = document.querySelector("canvas"), start : function (){ this.canvas.width = window.innerWidth; this.canvas.height = window.innerHeight; this.ctx = this.canvas.getContext('2d'); this.interval = setInterval(updateGameArea, 20); }, clear : function() { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); } } function CircComp(color, x , y){ this.x = x; this.y = y; context = GameArea.ctx; this.update = function(){ context.beginPath(); context.fillStyle = color; context.arc(this.x,this.y,this.radius,0,2*Math.PI); context.fill(); context.stroke(); } this.updateGameComp = function(){ GameArea.clear(); this.y += this.yAngle; this.x += this.xAngle; if(this.x + this.radius > GameArea.canvas.width){ this.xAngle = -1 * this.xAngle; } if(this.y + this.radius > GameArea.canvas.height){ this.yAngle = -1 * this.yAngle;; } if(this.x - this.radius < 0){ this.xAngle = -1 * this.xAngle; } if(this.y - this.radius < 0){ this.yAngle = -1 * this.yAngle; } this.update(); } } function updateGameArea(){ Ball.updateGameComp(); Ball1.updateGameComp(); } 
 <html> <head> <meta charset='urf-8'> <style> canvas{ border: 0px solid black; } body{ margin: 0; overflow: hidden; } </style> </head> <body onload='startGame()'> <canvas></canvas> <script src='Pong.js'></script> </body> </html> 

無論CircComp對象調用GameArea.clear()updateGameComp 繪制任何內容之前 ,您只應清除畫布一次(可能在updateGameArea

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM