Search code examples
javascriptcanvasrect

clearRect function not working in Javascript


I have some code that should be clearing a 50px wide gap in a rect(). But for some reason it isn't working. I've tried several different ways, but I can't seem to get it to work. Any help will be greatly appreciated!

My Code

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var rectWidth = 50;
var rectHeight = 50;
var rectRad = 25;
var x = (canvas.width / 2) - rectRad;
var y = canvas.height - 100;
var dx = 4;
var cw = canvas.width;
var ch = canvas.height;
var leftPressed = false;
var rightPressed = false;

function rect() {
  ctx.beginPath();
  ctx.rect(x, y, rectWidth, rectHeight);
  ctx.fillStyle = "#0095DD";
  ctx.fill();
  ctx.closePath();
}

function bar() {
  ctx.beginPath();
  ctx.clearRect(50, 0, 100, ch);
  ctx.rect(0, (ch / 2) - rectRad, cw, 50);
  ctx.fillStyle = "#FF9900";
  ctx.fill();
  ctx.closePath();
}



function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  rect();
  bar();

  if (leftPressed == true && x + dx > 0) {
    x -= dx;
  }

  if (rightPressed == true && x + dx < cw - rectWidth) {
    x += dx;
  }
}
setInterval(draw, 10);

document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);

function keyDownHandler(e) {
  if (e.keyCode === 37) {
    leftPressed = true;
  }

  if (e.keyCode === 39) {
    rightPressed = true;
  }
}

function keyUpHandler(e) {
  if (e.keyCode === 37) {
    leftPressed = false;
  }

  if (e.keyCode === 39) {
    rightPressed = false;
  }
}
* {
  padding: 0;
  margin: 0;
}

canvas {
  background: #eee;
  display: block;
  margin: 0 auto;
}
<canvas id="myCanvas" width="480" height="320"></canvas>


Solution

  • You're trying to clear the area in the rectangle before you draw the rectangle. You have to call clearRect after you call fill.

    Also, you're drawing it in the wrong spot slightly.

    function bar() {
      ctx.beginPath();
      ctx.rect(0, (ch / 2) - rectRad, cw, 50);
      ctx.fillStyle = "#FF9900";
      ctx.fill();
      ctx.closePath();
      ctx.clearRect(50, (ch/2) - 25, 50, 50); // this line
    }