私はバウンスボールのスクリプトを作成しましたが、もっと面白いように別のボールを追加しようとしました。しかし、私がしようとしているように、コードはうまく動作せず、別のボールを追加するように見える。私はそれを行うために同じ機能を使用したい、よりコンパクトでフレキシブルなので。キャンバスが複数のオブジェクトではなく単一のオブジェクトを表示しています
function startGame() {
GameArea.start();
\t Ball = new CircComp('red' , window.innerWidth/ 2 , window.innerHeight/2.5);
\t Ball.yAngle = 10;
\t Ball.xAngle = 10;
\t Ball.radius = 20; \t
\t Ball1 = new CircComp('green' , window.innerWidth/ 2 , window.innerHeight/2.5);
\t Ball1.yAngle = -10;
\t Ball1.xAngle = -10;
\t Ball1.radius = 20;
}
var GameArea = {
\t canvas : canvas = document.querySelector("canvas"),
\t start : \t function(){
\t \t this.canvas.width = window.innerWidth;
\t \t this.canvas.height = window.innerHeight;
\t \t this.ctx = this.canvas.getContext('2d');
\t \t this.interval = setInterval(updateGameArea, 20);
\t },
\t clear : function() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function CircComp(color, x , y){
\t this.x = x;
\t this.y = y;
\t context = GameArea.ctx;
\t this.update = function(){
\t \t context.beginPath();
\t \t context.fillStyle = color;
\t \t context.arc(this.x,this.y,this.radius,0,2*Math.PI);
\t \t context.fill();
\t \t context.stroke();
\t }
\t this.updateGameComp = function(){
\t \t GameArea.clear();
\t \t this.y += this.yAngle; \t
\t \t this.x += this.xAngle;
\t \t if(this.x + this.radius > GameArea.canvas.width){
\t \t \t this.xAngle = -1 * this.xAngle;
\t \t }
\t \t if(this.y + this.radius > GameArea.canvas.height){
\t \t \t this.yAngle = -1 * this.yAngle;; \t
\t \t }
\t \t if(this.x - this.radius < 0){
\t \t \t this.xAngle = -1 * this.xAngle;
\t \t } \t
\t \t if(this.y - this.radius < 0){
\t \t \t this.yAngle = -1 * this.yAngle;
\t \t }
\t \t this.update();
\t }
}
function updateGameArea(){
Ball.updateGameComp();
Ball1.updateGameComp();
}
<html>
\t <head>
\t \t <meta charset='urf-8'>
\t \t <style>
\t \t \t canvas{
\t \t \t \t border: 0px solid black;
\t \t \t }
\t \t \t body{
\t \t \t \t margin: 0;
\t \t \t \t overflow: hidden;
\t \t \t }
\t \t </style>
\t </head>
\t <body onload='startGame()'>
\t \t <canvas></canvas>
\t \t <script src='Pong.js'></script>
\t </body>
</html>
[この質問と私のここへの回答](http://stackoverflow.com/questions/42161164/javascrit-prototype-inheritance-and-html-canvas/42162355#42162355)を読んでください。問題はキャンバスの「コンテキスト」を再利用することにあります。 – chazsolo