【问题标题】:A function inside a function?函数中的函数?
【发布时间】:2012-11-26 07:08:30
【问题描述】:

我目前正在学习如何使用 Canvas,但我目前正试图将一个函数放入一个类中。

<script>
var c = document.getElementById("c");
var ctx = c.getContext("2d");

var disc = function(x,y,h,w,c1,c2,ctx){
  this.x=x;
  this.y=y;
  this.h=h;
  this.w=w;
  this.c1=c1;
  this.c2=c2;
  this.ctx=ctx;

}

disc.prototype.draw = function() {
  this.ctx.fillStyle=this.c1;
  this.ctx.fillRect(this.x,this.y,this.w,this.h/2);
  this.ctx.fillStyle=this.c2;
  this.ctx.fillRect(this.x,this.y+this.h/2,this.w,this.h/2);
}

disc.prototype.erase = function() {
  this.ctx.clearRect(this.x,this.y,this.w,this.h);
}


d1 = new disc(100,100,20,40,"#ff0000","#0000ff",ctx);

 var dx=1;
 var dy=1;

 function animate() {
      d1.erase();
      d1.x = d1.x + dx;
      d1.y = d1.y + dy;
      if ( d1.x>=500 || d1.x < 50)  { dx = dx * -1; d1.y = 40;}
      d1.draw();

  }

setInterval(animate,1);


</script>

如何将动画功能移动到光盘功能本身? 我已经尝试将它插入到光盘功能中:

  var dx=1;
  var dy=1;
  animate = function() {
      this.erase();
      this.x = this.x + dx;
      this.y = this.y + dy;
      if ( this.x>=500 || this.x < 50)  { dx = dx * -1; this.y = 40;}
      this.draw();
   }
 this.animate = animate;

还有变化

setInterval(d1.animate,1);

但它给了我

caught TypeError: Object [object Window] has no method 'erase' 

【问题讨论】:

  • 问题是当你的函数被setInterval调用时,在你的d1.animate()函数中this是全局对象(Window)。请改用setInterval(function(){d1.animate();},1);setInterval(d1.animate.bind(d1),1);。说到setInterval,你真的需要1ms的延迟吗?浏览器会将其四舍五入到 4 毫秒,但即使这样也比平滑动画所需的时间要小得多(20 毫秒将为您提供 50 fps)。
  • 另一方面,函数中的函数的技术术语是功能。强烈建议您现在深入三层以上,否则您将最终落入您的……某物的海岸。
  • “功能”? @davidisawesome 你真棒......

标签: javascript function canvas jquery-animate


【解决方案1】:

您需要将函数添加到discprototype,如下所示:

disc.prototype.animate = function(dx, dy) {
      this.erase();
      this.x = this.x + dx;
      this.y = this.y + dy;
      if ( this.x>=500 || this.x < 50)  { dx = dx * -1; this.y = 40;}
      this.draw();
};

setInterval(function() {
  d1.animate(1, 1);
},1);

【讨论】:

  • 噢噢噢!所以这就是在课堂上成功的意义
  • 添加到原型而不是直接添加是明智的,但这不是问题中的代码不起作用的原因(请参阅我上面的评论)。
  • 主要问题出在setInterval 部分。您可以通过this 直接添加该函数,虽然添加到原型中是一种更常见的做法,但这不是导致失败的主要原因。
猜你喜欢
  • 2017-08-22
  • 1970-01-01
  • 2022-06-26
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多