我目前正在学习如何使用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'
答案 0 :(得分:3)
您需要将此功能添加到prototype
的{{1}},如下所示:
disc