【问题标题】:Canvas beginPath() is not clearing rect before each frame画布 beginPath() 在每帧之前不清除矩形
【发布时间】:2017-06-24 03:37:00
【问题描述】:

我想在画布上为矩形设置动画。它在技术上是有效的,但画布在每一帧之前都没有清理干净,并且在地面上留下了一个标记(有点像蜗牛)。我已经进行了研究,一切似乎都指向使用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();
  };
}

【问题讨论】:

  • 你应该/可以使用ctx.clearRect(0, 0, canvas.width, canvas.height)来清除画布。

标签: javascript html animation canvas html5-canvas


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2015-02-01
    • 2011-08-01
    • 2011-07-28
    • 2015-09-24
    • 2011-03-25
    • 2017-06-16
    • 2019-12-16
    • 2017-05-11
    • 1970-01-01
    相关资源
    最近更新 更多