One reasonable approach would be to use a requestAnimationFrame
loop to update your X and Y, and draw again repeatedly. This would involve computing delta time, and using it to animate your coordinates. Here's an example jsfiddle:
//canvas
var c = document.getElementById("gameCanvas");
var ctx = c.getContext("2d");
//baseball
var baseball = new Image();
var drawFunc = function() {
//do animation logic
updateBall();
//draw new stuff
ctx.clearRect(0, 0, c.width, c.height);
ctx.drawImage(baseball, baseballX, baseballY);
//wait for next frame
//requestAnimationFrame(drawFunc);
//because the web is annoying, here's a hack to make it work
if (window.requestAnimationFrame) {
requestAnimationFrame(drawFunc);
} else if (window.webkitRequestAnimationFrame) {
webkitRequestAnimationFrame(drawFunc);
} else if (window.mozRequestAnimationFrame) {
mozRequestAnimationFrame(drawFunc);
}
};
baseball.onload = function() {
drawFunc();
};
baseball.src = "http://a3.mzstatic.com/us/r30/Purple6/v4/aa/65/fe/aa65fe9a-9a78-2abb-567c-d439c782d9c8/mzl.xwveiniy.175x175-75.jpg";
//ball movement
var baseballX = 0;
var baseballY = 0;
var lastTime = new Date().getTime();
var speed = 0.25;
var updateBall = function() {
//calculate time passed
var rightNow = new Date().getTime();
var elapsedTime = rightNow - lastTime;
lastTime = rightNow;
//animate
baseballX += speed * elapsedTime;
if (baseballX>300) baseballX = 0;
baseballY += speed * elapsedTime;
if (baseballY>425) baseballY = 0;
}
A less effective, but simpler, approach would be to use a fixed timestep. This can be achieved with a function like setInterval
or setTimeout
. Be warned there are issues with these routes: setInterval
might create a queue of frames to draw faster than they can be pushed. setTimeout
might leave you waiting too long for your next frame. With that said, here is another example jsfiddle
// main changes only
...
baseball.onload = function() {
setInterval(drawFunc, 1000/fps);
};
...
//ball movement
var baseballX = 0;
var baseballY = 0;
var fps = 48;
var speed = 0.25;
var updateBall = function() {
//calculate time passed
var elapsedTime = 1000 / fps;
...
EDIT: and just for completeness, an example showing the css 3 transitions method
.loading {
transition: 1s all;
-webkit-transition: 1s all;
-moz-transition: 1s all;
position: absolute;
top: 0px;
left: 0px;
}
.animated {
top: 250px;
left: 300px;
}