为什么这个if语句调用“draw()”函数?

时间:2018-06-01 01:29:48

标签: javascript canvas

有问题的代码是:

if (this.cCnt < 2) {
      this.draw();
    } else if (this.cCnt >= 2 && this.alpha >= 0) {
      this.alpha -= 0.1;
      this.draw();
      console.log('circle drawn');
    } else {
      console.log(this.x);
    }

我编写了上面的代码,试图在我的函数对象“Circle”中停止调用“this.draw”函数。出于某种原因,虽然(this.cCnt < 2)(this.cCnt >= 2 && this.alpha >= 0)的前两个条件证明为假,但代码仍然会继续跟踪“this.x”值,这可以通过在执行块中写入的控制台日志来证明“其他”。我试图做的是一旦视觉消失,就停止计算这个对象。但即使不透明度在视觉上是不可见的;物体仍在那里并在周围弹跳。如何让对象一起停止绘制/弹跳/存在?

以下整个代码段:

let canvas = document.getElementById('myCanvas');
let c = canvas.getContext('2d');

function Circle(x, y, arc, dx, dy, radius){
  this.x = x;
  this.y = y;
  this.dx = dx;
  this.dy = dy;
  this.arc = arc;
  this.cCnt = 0;
  this.alpha = 1;
  this.radius = radius;

  this.draw = function() {
    c.beginPath();
    //context.arc(x,y,r,sAngle,eAngle,counterclockwise);
    c.arc(this.x, this.y, this.radius, this.arc, Math.PI * 2, false); //
    c.globalAlpha = this.alpha;
    c.strokeStyle = 'pink';
    c.stroke();
  }

  this.update = function() {
    if (this.x + this.radius > canvas.width || this.x - this.radius < 0){
      this.dx = -this.dx;
      this.cCnt += 1;
    }
    if (this.y + this.radius > canvas.height || this.y - this.radius < 0){
      this.dy = -this.dy;
      this.cCnt += 1;
    }
    this.x += this.dx;
    this.y += this.dy;

    if (this.cCnt < 2) {
      this.draw();
    } else if (this.cCnt >= 2 && this.alpha >= 0) {
      this.alpha -= 0.1;
      this.draw();
      console.log('circle drawn');
    } else {
      console.log(this.x);
    }
  }
}

var circle = new Circle(20, 20, 0, 3, 3, 10); // x, y, arc, xVel, yVel, radius

function animate() {
  requestAnimationFrame(animate);
  c.clearRect(0, 0, canvas.width, canvas.height)
  circle.update();
}

animate();
body {
      background-color: black;
      margin: 0;
    }
<canvas id="myCanvas" width="80" height="60" style="background-color: white">

0 个答案:

没有答案