Yoshi moves around

Ultra basic animation proof of concept, as per request from StackOverflow

by Juan Muñoz

HTML

<body>
    <img id="sprite" src="http://petiteleve.free.fr/SO/yoshi.png" />
    <p>Click the buttons below to handle animation</p>
    <input type="button" value="Left"  onmousedown="move(-1);" onmouseup="stop()"/>
    <input type="button" value="Right" onmousedown="move( 1);" onmouseup="stop()"/>
</body>

CSS

/* needed for the img to be free to move around */
#sprite { position:relative; }

JavaScript

var timer_id; // reference of the timer, needed to stop it
var speed = 50; // pixels/second
var period = 40; // milliseconds
var sprite; // the element that will move
var sprite_speed = 0; // move per period
var sprite_position = 100; // pixels

// called every 40 ms
function animate ()
{
    sprite_position += sprite_speed;
    if (sprite_position < 0) sprite_position = 0;
    if (sprite_position > 200) sprite_position = 200;
    sprite.style.left = sprite_position+'px';
}

// launches a move in one direction (-1 for left, 1 for right)
function move(direction)
{
    if (timer_id) stop();
    sprite_speed = speed * period/1000 * direction;
    timer_id = setInterval (animate, period);
}

// stops animation
function stop()
{
    clearInterval (timer_id);
    timer_id = null;
}

// init (once the page has loaded)
function init()
{
    // get a reference to the HTML element we will move
    sprite = document.getElementById ("sprite"); 
    animate(); // just to initialize sprite position
}

// start doing things once the page has loaded
window.onload =init;