clearRect函数在Javascript中不起作用

时间:2017-07-17 20:44:27

标签: javascript canvas clear rect

我有一些代码应该在rect()中清除50px宽的间隙。但由于某种原因,它不起作用。我尝试了几种不同的方式,但我似乎无法让它发挥作用。任何帮助将不胜感激!

我的代码



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;
  }
}
&#13;
* {
  padding: 0;
  margin: 0;
}

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

1 个答案:

答案 0 :(得分:1)

您在绘制矩形之前尝试清除矩形区域。调用fill后,您必须调用clearRect。

另外,你稍微在错误的地方画画。

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
}