如何在HTML5 Canvas中拥有多个颜色元素?

时间:2017-09-05 02:07:23

标签: javascript html5 canvas

我完成了一个tutorial to make a PONG game with HTML5 and JavaScript,我想知道如何更改元素的颜色,这样每个球拍都是不同的颜色,球是不同的颜色。每当我尝试单独为元素着色时,它们都会改变颜色。

1 个答案:

答案 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>
&#13;
&#13;
&#13;