【发布时间】: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