我目前正在學習如何使用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'
的問題是,你的'd1.animate內()''函數是this'全局對象('Window')當你的功能是由'setInterval'調用。嘗試'setInterval(function(){d1.animate();},1);'或'setInterval(d1.animate.bind(d1),1);'而不是。說到'setInterval',你真的需要1ms的延遲嗎?瀏覽器將四捨五入到四分之一,但即使這樣比平滑動畫所需要的還要小(20毫秒會給你50fps)。 – nnnnnn
作爲一個方面,功能內的功能的技術術語是funception。這是非常可取的,你現在做的深度超過三個層次,否則你會在你的..的東西。 – ledgeJumper
「音樂」? @davidisawesome你_are_真棒... – nnnnnn