HTML,CSS,JS,Canvas矩形不删除

时间:2017-05-04 13:05:45

标签: javascript html css canvas

我希望矩形在画布上移动而不是每次都复制。 它绘制它然后矩形停留在那里。

我是画布的初学者,所以如果它是史诗般的失败,那么请做好准备。

codepen位于LINK

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");

var WIDTH = canvas.width;
var HEIGHT = canvas.height;
var boxWidth = 50;
var boxHeight = 50;
var bX = WIDTH / 2 - boxWidth / 2;
var bY = HEIGHT / 2 - boxHeight / 2;

function render() {
  ctx.fillStyle = "white";
  ctx.rect(bX, bY, boxWidth, boxHeight);
  ctx.fill();
}

function control() {
  bX++;
}

function main() {
  control();
  render();
}

main();
var run = setInterval(main, 10)
canvas {
  width: 400px;
  height: 400px;
  background-color: black;
}

div {
  text-align: center;
}
<div>
  <canvas width="400px" height="400px" background-color="black" id="canvas"></canvas>
</div>

1 个答案:

答案 0 :(得分:1)

每次绘制矩形之前重新绘制画布 - 考虑一下。它全部分层完成。

矩形是“停留在那里”,因为你没有替换上次绘制的矩形。

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");

var WIDTH = canvas.width;
var HEIGHT = canvas.height;
var boxWidth = 50;
var boxHeight = 50;
var bX = WIDTH / 2 - boxWidth / 2;
var bY = HEIGHT / 2 - boxHeight / 2;

function render() {

  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); //use clear rect instead

  ctx.fillStyle = "white";
  ctx.fillRect(bX, bY, boxWidth, boxHeight); //use fillRect instead of fill()

}

function control() {
  bX++;
}

(function main() {
  control();
  render();

  requestAnimationFrame(()=>main());
})()

   
canvas {
  width: 400px;
  height: 400px;
  background-color: black;
}

div {
  text-align: center;
}
<html>

<head></head>

<body>
  <div>
    <canvas width="400px" height="400px" background-color="black" id="canvas"></canvas>
  </div>
</body>

</html>

另请参阅requestAnimationFrame()方法而不是setInterval - 它与窗口的javascript计时器同步,不太可能导致问题。