2017-09-05 156 views
-1

我完成了一个tutorial to make a PONG game with HTML5 and JavaScript,我想知道如何改变元素的颜色,以便每个桨是不同的颜色,球是不同的颜色。每当我尝试单独给一个元素着色时,他们都会改变颜色。如何在HTML5 Canvas中使用多个颜色元素?

+0

下一次请包含您尝试和没有工作的代码。查明错误通常比从头开始添加更容易。 –

+0

该网站已在底部完成产品并链接了一个jfiddle [链接](http://jsfiddle.net/mailson/kt3Md/5/?utm_source=website&utm_medium=embed&utm_campaign=kt3Md) – Ethan

+0

我并不是指游戏,我的意思是你试图对画布上的元素着色的代码。在链接的文章中没有任何颜色。 –

回答

1

您可以通过更改上下文中的fillStyle来给任何新的矩形上色。请记住,您需要在绘图之后将其重置,否则其他所有未明确着色的颜色也将变为该颜色。

在此示例中,我已将一个参数添加到Paddle,该参数将颜色设置为属性。在绘图方法中,它用于设置上下文颜色,并在之后立即重置。

我会把球留给你挑战。

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>