2017-09-05 5 views
-1

私はtutorial to make a PONG game with HTML5 and JavaScriptを完成し、どのようにして各パドルが異なる色でボールが異なる色になるように要素の色を変えることができるのだろうと思っていました。要素を個別に色付けしようとするたびに、すべて色が変わります。HTML5 Canvasで複数の色要素を使用するにはどうすればいいですか?

+0

次の時間は、あなたがうまくいかなかった試み、コードを含めてください。通常、何かをゼロから追加するのではなく、エラーを特定する方が簡単です。 –

+0

サイトは完成品を下に持っていて、jfiddle [link](http://jsfiddle.net/mailson/kt3Md/5/?utm_source=website&utm_medium=embed&utm_campaign=kt3Md) – Ethan

+0

にリンクしています。私はあなたがキャンバス上の要素を色付けしようとしたコードを意味しました。リンクされた記事では何も着色されていません。 –

答えて

1

コンテキスト上でfillStyleを変更すると、新しい矩形の色を付けることができます。ただし、描画後にリセットする必要があることを覚えておいてください。そうでない場合は、明示的に色付けされていないものもその色になります。

この例では、色を属性として設定するパラメータをPaddleに追加しました。 drawメソッドでは、コンテキストカラーの設定に使用され、直後にリセットされます。

私はあなたに挑戦としてボールを残します。

function Game() { 
 
    var canvas = document.getElementById("game"); 
 
    this.width = canvas.width; 
 
    this.height = canvas.height; 
 
    this.context = canvas.getContext("2d"); 
 
    this.context.fillStyle = "white"; 
 
    
 
    this.p1 = new Paddle(5, 0, "yellow"); 
 
    this.p1.y = this.height/2 - this.p1.height/2; 
 
    this.p2 = new Paddle(this.width - 5 - 2, 0, "lime"); 
 
    this.p2.y = this.height/2 - this.p2.height/2; 
 
} 
 

 
Game.prototype.draw = function() 
 
{ 
 
    this.context.clearRect(0, 0, this.width, this.height); 
 
    this.context.fillRect(this.width/2, 0, 2, this.height); 
 
    
 
    this.p1.draw(this.context); 
 
    this.p2.draw(this.context); 
 
}; 
 
    
 
Game.prototype.update = function() 
 
{ 
 
    if (this.paused) 
 
     return; 
 
}; 
 

 

 
// PADDLE 
 
function Paddle(x,y, color) { 
 
    this.x = x; 
 
    this.y = y; 
 
    this.width = 2; 
 
    this.height = 28; 
 
    this.score = 0; 
 
    this.color = color 
 
} 
 

 
Paddle.prototype.draw = function(p) 
 
{ 
 
    var oldStyle = p.fillStyle 
 
    p.fillStyle = this.color 
 
    p.fillRect(this.x, this.y, this.width, this.height); 
 
    p.fillStyle = oldStyle 
 
}; 
 

 

 
// Initialize our game instance 
 
var game = new Game(); 
 
    
 
function MainLoop() { 
 
    game.update(); 
 
    game.draw(); 
 
    // Call the main loop again at a frame rate of 30fps 
 
    setTimeout(MainLoop, 33.3333); 
 
} 
 
    
 
// Start the game execution 
 
MainLoop();
#game { 
 
    background-color: #353535; 
 
}
<!DOCTYPE HTML> 
 
<html> 
 
    <head> 
 
     <title>Pong</title> 
 
    </head> 
 
    <body> 
 
     <canvas id="game" width="512" height="256"></canvas> 
 
    </body> 
 
</html>

関連する問題