I wrote simple class in JS witch works, but i had problem when i try use setInterval with it. Ex. if i do something like that
ball = new ball(5,10,0, '#canvas');
ball.draw();
ball.draw();
ball.draw();
ball.draw();
It works. But this:
ball = new ball(5,10,0, '#canvas');
setInterval(ball.draw, 100);
Not work. I get error that values are undefined.
function ball (x,y,z,holdingEl) {
this.r = 5; //zmienna przechowujaca promien pilki
this.size = this.r *2; // zmienna przechowujaca rozmiar
this.ballSpeed = 100; // predkosc pilki
this.ballWeight = 0.45; // masa pilki
this.maxFootContactTime = 0.2; // maksymalny czas kontaktu pilki z noga - stala
this.ctx = jQuery(holdingEl)[0].getContext("2d"); // obiekt pilki
this.intVal = 100 // predkosc odswiezania
this.currentPos = { // wspolrzedn开发者_如何学Pythone pozycji
x: x,
y: y,
z: z
}
this.interactionPos = { // wspolrzedne pozycji ostatniej interakcji
x: -1,
y: -1,
z: -1
}
this.direct = { // kierunek w kazdej plaszczyznie
x : 1,
y : 0,
z : 0
}
this.draw = function (){
this.ctx.clearRect(0,0,1100,800);
this.ctx.beginPath();
this.ctx.arc(this.currentPos.x, this.currentPos.y, this.r, 0, Math.PI*2, true);
this.ctx.closePath();
this.ctx.fill();
}
}
Guessing it is because you're sending a reference to the function itself, which is not geting called from the context of ball
.
Do this instead:
ball = new ball(5,10,0, '#canvas');
setInterval(function() {
ball.draw();
}, 100);
Using your first code, within the draw()
function, this
is the ball
instance.
Using your setInterval()
code, this
will be window
in the draw()
function.
Try this
ball = new ball(5,10,0, '#canvas');
f = function() {
ball.draw()
}
setInterval(f, 100)
精彩评论