简体   繁体   中英

Simple ball animation HTML5 using requestAnimationFrame

I am just starting trying to make some animation using HTML5 and JavaScript. Currently I have created a JavaScript class for the ball. It has an update function which should update the position of the ball and a draw function which should draw it:

 /*global Vector*/
var Ball = (function () {
function Ball(pPostion) {
    this.setPosition(pPostion);
}

Ball.prototype.getPosition = function () {
    return this.mPosition;
};
Ball.prototype.setPosition = function (pPosition) {
    this.mPosition = pPosition;
};
Ball.prototype.draw = function (pContext) {
    pContext.save();
    pContext.beginPath();
    pContext.arc(100, 100, 20, 0, Math.PI * 2, true);
    pContext.closePath();
    pContext.fillStyle = '#ff0000';
    pContext.stroke();
    pContext.restore();
};

Ball.prototype.update = function () {
    this.getPosition().add(new Vector(10, 0));
};

return Ball;
}());

In the my main section I have created the following method:

function ballGameLoop() {
    ball.draw(mainContext);
    ball.update();
    requestAnimationFrame(ballGameLoop);
}

And when called, it does draw the ball but it doesn't seem to move at all. I don't have a specific type of way I want the ball to be animated, just any kind of movement would be good. Can anyone give any advice on where I may be going wrong?

From the looks of it, it seems you are just drawing an arc at the same coordinates over and over again (center at (100,100)).

Incorporating your Ball's position into this would be the way to make the render location dependent on the object's position. From what it seems, something along the lines of the following would give movement:

Ball.prototype.draw = function (pContext) {
    var coordinates = this.getPosition();
    pContext.save();
    pContext.beginPath();
    pContext.arc(coordinates.X, coordinates.Y, 20, 0, Math.PI * 2, true);
    pContext.closePath();
    pContext.fillStyle = '#ff0000';
    pContext.stroke();
    pContext.restore();
};

I'm of course assuming on how you setup the Vector object, so I'm guessing x and y can be accessed by (Vector).X and (Vector).Y respectively.

anyway just my approach at it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM