首页 > 解决方案 > 调用函数时如何取消绘制矩形

问题描述

我想制作一个从右向左移动的矩形。

我可以在前一个矩形的左侧绘制一个新矩形,但我无法擦除前一个矩形。

这是我的代码:

let cvs = document.getElementById("canvas");
let ctx = cvs.getContext('2d');
let firstpos = 400;

let blocks = [];
blocks[0] = {
  x: 400,
  y: Math.floor(Math.random() * 360)
}

function draw() {
  for (var i = 0; i < blocks.length; i++) {
    ctx.beginPath()
    ctx.fillStyle = "white";
    ctx.fillRect(blocks[i].x, 0, 70, blocks[i].y);
    ctx.fill();
    blocks[i].x -= 0;
  }
  requestAnimationFrame(draw);
}
draw()
#canvas {
  background-color: #000;
}
<canvas id="canvas" width="1000" height="500"></canvas>

标签: javascripthtml5-canvas

解决方案


工作片段

利用CanvasRenderingContext2D.clearRect()

let cvs = document.getElementById("canvas");
let ctx = cvs.getContext('2d');
let firstpos = 400;

let blocks = [];
blocks[0] = {
  x: 0,
  y: Math.floor(Math.random() * 360)
}

function draw() {
  blocks[0].x++;
  ctx.clearRect(0, 0, canvas.width, canvas.height); // canvas clear up
  for (var i = 0; i < blocks.length; i++) {
    ctx.beginPath()
    ctx.fillStyle = "white";
    ctx.fillRect(blocks[i].x, 0, 70, blocks[i].y);
    ctx.fill();
    blocks[i].x -= 0;
  }
  
  requestAnimationFrame(draw);
}
setInterval(draw, 500)
#canvas {
  background-color: #000;
}
<canvas id="canvas" width="1000" height="500"></canvas>


推荐阅读