2017-09-05 2 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>

관련 문제