Basic animation with JavaScript

by Eduardo Lázaro

HTML

<body>	
		<div id="camara">
    <div id="fondo_1"  ></div>
			<div id="fondo_2"  ></div>
			<div id="avion" ></div>
		</div>

		<div id="controles">
			<input type="button" name="Parar" value="parar" onclick="anim.parar()" />
			<input type="button" name="Arrancar" value="arrancar" onclick="anim.arrancar()" />
			<b>Elige la velocidad</b>
			<select name="vel" onchange="anim.cambiarVelocidad(this.value);">
				<option value="0.2" >Muy lento</option>
				<option value="0.5" >Lento</option>
				<option selected value="1" >Normal</option>
				<option value="2" >Rápido</option>
				<option value="4" >Muy Rápido</option>
			</select>
		</div>
	</body>

CSS

#camara{
	position: relative;
	float: left;
	height: 349px;
	width:620px;
	overflow:hidden;
}

#fondo_1 {
	position: absolute;
	top: 0px;
	left: 0px;
	width: 620px;
	height: 349px;
  background-color:#404040;
}

#fondo_2{
	position: absolute;
	top: 0px;
	left: 0px;
	width: 620px;
	left:620px;
	height: 349px;
	-moz-transform: scaleX(-1);
	-o-transform: scaleX(-1);
	-webkit-transform: scaleX(-1);
	transform: scaleX(-1);
	filter: FlipH;
	-ms-filter: "FlipH";
  background-color:#909090;
}

#avion {
	position: absolute;
	top: 30px;
	left: 50px;
	width: 50px; height:30px;
  background-color:#dcdcdc;
}

#controles{
	position:relative;
	margin-top: 20px;
	float:left;
	width:100%;
}

JavaScript

window.onload = function() {
	anim= new animacion('avion', 'fondo_1', 'fondo_2');
	anim.arrancar();
}

animacion = function (id_avion, id_fondo_1, id_fondo_2) {
	this.avion=document.getElementById(id_avion);
	this.fondo_1=document.getElementById(id_fondo_1);
	this.fondo_2=document.getElementById(id_fondo_2);
	this.posicion_fondo_1=0;
	this.posicion_fondo_2=620;
	this.velocidad=1;
	this.intervalo;
};

animacion.prototype.arrancar = function(){
	var that=this;
	clearInterval(this.intervalo);
	this.intervalo=setInterval(function() { that.animar(); }, 16 ); 
}

animacion.prototype.parar = function(){
	clearInterval(this.intervalo);
}

animacion.prototype.cambiarVelocidad = function(velocidad){
	this.velocidad=velocidad;
}

animacion.prototype.animar = function(){
	this.posicion_fondo_1-=this.velocidad; this.posicion_fondo_2-=this.velocidad;
	
	if(this.posicion_fondo_1<=-620) { this.posicion_fondo_1=this.posicion_fondo_2+620; }
	if(this.posicion_fondo_2<=-620) { this.posicion_fondo_2=this.posicion_fondo_1+620; }
	
	document.getElementById('fondo_1').style.left=(this.posicion_fondo_1)+'px';
	document.getElementById('fondo_2').style.left=(this.posicion_fondo_2)+'px';
}