user11777421
user11777421

Reputation:

Filling in two colors while using the rect() method

I was trying to make two different shapes that are different colors but it isn't working. Both of the shapes are the same colors. Please help!(Please note that I am not the best coder in the world)

I've looked for other examples on this website, but all of them use the lineTo() method and I would like to use the rect() method just to make things easier.

//make canvas and set it up
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');

canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
canvas.style.position = 'absolute';
canvas.style.left = '0px';
canvas.style.top = '0px';
canvas.style.backgroundColor = '#D0C6C6';
var cH = canvas.height;
var cW = canvas.width;

//draw paddles

//variables
var paddleLength = 120;
var redPaddleY = window.innerHeight / 2;
var bluePaddleY = window.innerHeight / 2;
var paddleWidth = 20;
//drawing starts
function drawPaddles() {
    //RED PADDLE
    var redPaddle = function(color) {
    ctx.fillStyle = color;
    ctx.clearRect(0, 0, cW, cH);
    ctx.rect(cH / 12, redPaddleY - paddleLength / 2, paddleWidth, paddleLength);
    ctx.fill();
    };
    //BLUE PADDLE
    var bluePaddle = function(color) {
    ctx.fillStyle = color;
    ctx.clearRect(0, 0, cW, cH);
    ctx.rect(cH / 12 * 14, bluePaddleY - paddleLength / 2, paddleWidth, paddleLength);
    ctx.fill();
    };
    redPaddle('red');
    bluePaddle('blue');
};
var interval = setInterval(drawPaddles, 25);

Upvotes: 0

Views: 38

Answers (1)

Synthetx
Synthetx

Reputation: 609

Whenever you add a shape to the canvas it becomes part of the current path. The current path remains open until you tell the canvas to start a new one with beginPath(). This means that when you add your second rect() it is combined with the first and filled with the same colour.

The simplest fix would be to use the fillRect() function instead of rect which begins, closes and fills a path in one call.

var redPaddle = function(color) {
  ctx.fillStyle = color;
  ctx.fillRect(cH / 12, redPaddleY - paddleLength / 2, paddleWidth, paddleLength);
};

If you still want to use rect() you should tell the canvas to begin a new path for each paddle.

var redPaddle = function(color) {
  ctx.fillStyle = color;
  ctx.beginPath();
  ctx.rect(cH / 12, redPaddleY - paddleLength / 2, paddleWidth, paddleLength);
  ctx.fill();
};

I would also suggest moving the clearRect() outside of the drawing functions too. Clear once per frame and draw both paddles.

...    
ctx.clearRect(0, 0, cW, cH);
redPaddle();
bluePaddle();
...

You should also investigate requestAnimationFrame() to do your animation loop as it provides many performance improvements over intervals.

Upvotes: 1

Related Questions