Canvas beginPath()在每帧之前没有清除rect

时间:2017-06-23 19:13:34

标签: javascript html5 animation canvas html5-canvas

我想在画布上设置矩形动画。它在技术上有效,但画布在每一帧之前都没有清理,它在地面上留下了一个标记(有点像蜗牛)。我已经做过研究,一切似乎都指向使用ctx.beginPath()作为我的问题的解决方案,但是当我尝试在这里使用它时,它不起作用。我做错了什么?

这是原始javascript:

// create a canvas element
var canvas = document.createElement("canvas");

// attach element to DOM
document.getElementsByTagName("body")[0].appendChild(canvas);

// get the canvas context (this is the part we draw to)
var ctx = canvas.getContext("2d");
var bug = new Bug(0,0);

function setup() {
  // setup the canvas size to match the window
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  // set the 0,0 point to the middle of the canvas
  ctx.translate(canvas.width / 2, canvas.height / 2);
}

function draw() { //Do the drawing
  ctx.beginPath();
  bug.update();
  bug.draw();
  window.requestAnimationFrame(function(){draw()});
}

// start enterFrame loop
window.requestAnimationFrame(draw);

// force running setup
setup();

// re-setup canvas when the size of the window changes 
window.addEventListener("resize", setup);

// sin(pi) == 0
// cos(pi) == -1
// sin(2pi) == 0
// cos(2pi) == 1
// degrees to radians: {{ deg * (pi/180) = rad }}

function randomRange(max, min) {
  return Math.floor(Math.random() * (max - min) + min);
}

function Bug(x, y) {
  this.x = x;
  this.y = y;
  this.jitter = 10;
  this.speed = 1;
  this.deg = 0;
  this.rad = 0;
  this.update = function() {
    //update degrees
    this.deg += randomRange(this.jitter, -this.jitter);
    //convert degrees into radians
    this.rad = this.deg * (Math.PI/180);
    //update coordinates
    this.x += this.speed * (Math.cos(this.rad));
    this.y += this.speed * (Math.sin(this.rad));
  };
  this.draw = function() {
    ctx.beginPath();
    ctx.rect(this.x, this.y, 50, 50);
    ctx.fill();
  };
}

1 个答案:

答案 0 :(得分:0)

beginPath函数不会清除它开始绘制路径的屏幕,要清除屏幕,应该使用clearRect,在特定情况下你应该使用:

ctx.clearRect(-canvas.width, -canvas.height, canvas.width*2, canvas.height*2);