2012-12-08 35 views
2

我目前正在學習如何使用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' 
+1

的問題是,你的'd1.animate內()''函數是this'全局對象('Window')當你的功能是由'setInterval'調用。嘗試'setInterval(function(){d1.animate();},1);'或'setInterval(d1.animate.bind(d1),1);'而不是。說到'setInterval',你真的需要1ms的延遲嗎?瀏覽器將四捨五入到四分之一,但即使這樣比平滑動畫所需要的還要小(20毫秒會給你50fps)。 – nnnnnn

+2

作爲一個方面,功能內的功能的技術術語是funception。這是非常可取的,你現在做的深度超過三個層次,否則你會在你的..的東西。 – ledgeJumper

+1

「音樂」? @davidisawesome你_are_真棒... – nnnnnn

回答

3

您需要的功能添加到prototypedisc,象下面這樣:

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); 
+0

ooohhhh!所以這是什麼意思,讓它在類 – user1869558

+1

添加到原型,而不是直接是明智的,但它不是爲什麼在問題的代碼沒有工作(見上面我的意見)。 – nnnnnn

+1

主要問題在'setInterval'部分。你可以通過'this'直接添加函數,雖然添加到原型是一種更常見的做法,但這不是導致失敗的主要原因。 –