繁体   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