lunes, 19 de septiembre de 2011

Secuencia de imágenes con JavaScript

Dado el siguiente código en JavaScript, correspondiente a una secuencia de imágenes:

var SecuenciaID = null
var imagen = 0
var duracion = 1000
	
{imagenes = new CreaArray(4)
imagenes[1].src = "img/g1.jpg"
imagenes[2].src = "img/g2.png"
imagenes[3].src = "img/g3.jpg"
imagenes[4].src = "img/g4.jpg"
}
		
function CreaArray(n) {
	this.length = n
	for (var i = 1; i<=n; i++) {
		this[i] = new Image()
	}
	return this
}
		
function MostrarSecuencia() {
	{
		document.images["secuencia"].src = imagenes[imagen].src
		imagen++
		if ( imagen == 5 )
			imagen = 1
	}
	SecuenciaID = setTimeout("MostrarSecuencia()", duracion)
	SecuenciaEjecutandose = true
}
		
function IniciarSecuencia() {
	imagen = 1
	MostrarSecuencia()
}

Realizar los siguientes ejercicios:
  1. Conseguir que se muestre la secuencia de imágenes.
  2. Hacer que el tiempo durante el cual se muestra cada imagen sea distinto.
  3. Modificar el tamaño de cada imagen.
  4. Añadir música de fondo (debe estar sonando continuamente).
  5. Hacer que cuando termine la música de fondo, se pare la secuencia de imágenes.
  6. Añadir botones que inicien o paren la secuencia.
NOTA: en los cuatro primero ejercicios, el código JavaScript se añadió directamente dentro del código HTML, pero en los dos últimos, se creó un fichero por separado al que se referenciaba desde la cabecera del HTML.

EJERCICIO 1

<html>
	<script language="javascript" type="text/javascript">
		
		var SecuenciaID = null
		var imagen = 0
		var duracion = 1000
		
		{imagenes = new CreaArray(4)
		imagenes[1].src = "img/g1.jpg"
		imagenes[2].src = "img/g2.png"
		imagenes[3].src = "img/g3.jpg"
		imagenes[4].src = "img/g4.jpg"
		}
		
		function CreaArray(n) {
			this.length = n
			for (var i = 1; i<=n; i++) {
				this[i] = new Image()
			}
			return this
		}
		
		function MostrarSecuencia() {
			{
				document.images["secuencia"].src = imagenes[imagen].src
				imagen++
				if ( imagen == 5 )
					imagen = 1
			}
			SecuenciaID = setTimeout("MostrarSecuencia()", duracion)
			SecuenciaEjecutandose = true
		}
		
		function IniciarSecuencia() {
			imagen = 1
			MostrarSecuencia()
		}
		
	</script>
	
	<body onload="IniciarSecuencia()">
		<p><img src="img/g1.jpg" alt="Secuencia" name="secuencia"></p>
	</body>
</html>

EJERCICIO 2

<html>
	<script language="javascript" type="text/javascript">
		<!-- DECLARACIÓN DE VARIABLES -->
		var SecuenciaID = null
		var imagen = 0
		var tiempo = 1
		
		<!-- ARRAY DE IMÁGENES -->
		{imagenes = new CreaArray(4)
		imagenes[1].src = "img/g1.jpg"
		imagenes[2].src = "img/g2.png"
		imagenes[3].src = "img/g3.jpg"
		imagenes[4].src = "img/g4.jpg"
		}
		
		<!-- ARRAY DE "DURACIONES". Tiempo durante el cual se mostrará cada imagen -->
		{duracion = new CreaArray2(4)
		duracion[1] = 1000
		duracion[2] = 2000
		duracion[3] = 3000
		duracion[4] = 4000
		}
		
		<!-- FUNCIONCES QUE DEBEMOS DEFINIR PARA CREAR LOS ARRAYS -->
		function CreaArray(n) {
			<!-- DEFINIMOS EL TAMAÑO DEL ARRAY -->
			this.length = n
			for (var i = 1; i<=n; i++) {
				this[i] = new Image()
			}
			return this
		}
		
		function CreaArray2(n) {
			this.length = n
			for (var i = 1; i<=n; i++) {
				this[i] = 0
			}
			return this
		}
		
		function MostrarSecuencia() {
			{
				<!-- A TODAS LAS IMÁGENES DE <body> CUYO NOMBRE SEA "Secuencia" -->
				<!-- LE ASIGNAMOS LAS DEL ARRAY -->
				document.images["secuencia"].src = imagenes[imagen].src
				<!-- INCREMENTA EL VALOR DE "imagen" PARA QUE A CADA VUELTA MUESTRE LA -->
				<!-- SIGUIENTE SI LLEGA AL FINAL, COMIENZA POR LA PRIMERA DE NUEVO. -->
				imagen++
				if ( imagen == 5 )
					imagen = 1
			}
			<!-- setTimeout PERMITE EJECUTAR UNA FUNCIÓN PASADO CIERTO TIEMPO. -->
			SecuenciaID = setTimeout("MostrarSecuencia()", duracion[tiempo])
			tiempo++
			if ( tiempo == 5 )
				tiempo = 1
			SecuenciaEjecutandose = true
		}
		
		function IniciarSecuencia() {
			imagen = 1
			MostrarSecuencia()
		}
		
	</script>
	
	<body onload="IniciarSecuencia()">
		<p><img src="img/g1.jpg" alt="Secuencia" name="secuencia"></p>
	</body>
</html>

EJERCICIO 3

<html>
	<script language="javascript" type="text/javascript">
		<!-- DECLARACIÓN DE VARIABLES -->
		var SecuenciaID = null
		var imagen = 0
		var tiempo = 1
		
		<!-- ARRAY DE IMÁGENES -->
		{imagenes = new CreaArray(4)
		imagenes[1].src = "img/g1.jpg"
		imagenes[2].src = "img/g2.png"
		imagenes[3].src = "img/g3.jpg"
		imagenes[4].src = "img/g4.jpg"
		}
		
		<!-- ARRAY DE "DURACIONES". Tiempo durante el cual se mostrará cada imagen -->
		{duracion = new CreaArray2(4)
		duracion[1] = 1000
		duracion[2] = 2000
		duracion[3] = 3000
		duracion[4] = 4000
		}
		
		<!-- ARRAY DE "TAMAÑOS". Tamaño que irá tomando cada imagen -->
		{size = new CreaArray2(4)
		size[1] = 100
		size[2] = 200
		size[3] = 300
		size[4] = 400
		}
		
		<!-- FUNCIONCES QUE DEBEMOS DEFINIR PARA CREAR LOS ARRAYS -->
		function CreaArray(n) {
			<!-- DEFINIMOS EL TAMAÑO DEL ARRAY -->
			this.length = n
			for (var i = 1; i<=n; i++) {
				this[i] = new Image()
			}
			return this
		}
		
		function CreaArray2(n) {
			this.length = n
			for (var i = 1; i<=n; i++) {
				this[i] = 0
			}
			return this
		}
		
		function MostrarSecuencia () {
			{
				<!-- DEFINIR TAMAÑO DE LAS IMÁGENES -->
				document.images["secuencia"].width = size[imagen]
				document.images["secuencia"].height = size[imagen]
				
				<!-- A TODAS LAS IMÁGENES DE <body> CUYO NOMBRE SEA "Secuencia" -->
				<!-- LE ASIGNAMOS LAS DEL ARRAY -->
				document.images["secuencia"].src = imagenes[imagen].src
				<!-- INCREMENTA EL VALOR DE "imagen" PARA QUE A CADA VUELTA MUESTRE LA -->
				<!-- SIGUIENTE SI LLEGA AL FINAL, COMIENZA POR LA PRIMERA DE NUEVO. -->
				imagen++
				if ( imagen == 5 )
					imagen = 1
			}
			<!-- setTimeout PERMITE EJECUTAR UNA FUNCIÓN PASADO CIERTO TIEMPO. -->
			SecuenciaID = setTimeout("MostrarSecuencia()", duracion[tiempo])
			tiempo++
				if ( tiempo == 5 )
					tiempo = 1
			SecuenciaEjecutandose = true
		}
		
		function IniciarSecuencia() {
			imagen = 1
			MostrarSecuencia()
		}
		
	</script>
	
	<body onload="IniciarSecuencia()">
		<p><img src="img/g1.jpg" alt="Secuencia" name="secuencia"></p>
	</body>
</html>

EJERCICIO 4

<html>
	<script language="javascript" type="text/javascript">
		<!-- DECLARACIÓN DE VARIABLES -->
		var SecuenciaID = null
		var imagen = 0
		var tiempo = 1
		
		<!-- ARRAY DE IMÁGENES -->
		{imagenes = new CreaArray(4)
		imagenes[1].src = "img/g1.jpg"
		imagenes[2].src = "img/g2.png"
		imagenes[3].src = "img/g3.jpg"
		imagenes[4].src = "img/g4.jpg"
		}
		
		<!-- ARRAY DE "DURACIONES". Tiempo durante el cual se mostrará cada imagen -->
		{duracion = new CreaArray2(4)
		duracion[1] = 1000
		duracion[2] = 2000
		duracion[3] = 3000
		duracion[4] = 4000
		}
		
		<!-- ARRAY DE "TAMAÑOS". Tamaño que irá tomando cada imagen -->
		{size = new CreaArray2(4)
		size[1] = 100
		size[2] = 200
		size[3] = 300
		size[4] = 400
		}
		
		<!-- FUNCIONCES QUE DEBEMOS DEFINIR PARA CREAR LOS ARRAYS -->
		function CreaArray(n) {
			<!-- DEFINIMOS EL TAMAÑO DEL ARRAY -->
			this.length = n
			for (var i = 1; i<=n; i++) {
				this[i] = new Image()
			}
			return this
		}
		
		function CreaArray2(n) {
			this.length = n
			for (var i = 1; i<=n; i++) {
				this[i] = 0
			}
			return this
		}
		
		function MostrarSecuencia () {
			{
				<!-- DEFINIR TAMAÑO DE LAS IMÁGENES -->
				document.images["secuencia"].width = size[imagen]
				document.images["secuencia"].height = size[imagen]
				
				<!-- A TODAS LAS IMÁGENES DE <body> CUYO NOMBRE SEA "Secuencia" -->
				<!-- LE ASIGNAMOS LAS DEL ARRAY -->
				document.images["secuencia"].src = imagenes[imagen].src
				<!-- INCREMENTA EL VALOR DE "imagen" PARA QUE A CADA VUELTA MUESTRE LA -->
				<!-- SIGUIENTE SI LLEGA AL FINAL, COMIENZA POR LA PRIMERA DE NUEVO. -->
				imagen++
				if ( imagen == 5 )
					imagen = 1
			}
			<!-- setTimeout PERMITE EJECUTAR UNA FUNCIÓN PASADO CIERTO TIEMPO. -->
			SecuenciaID = setTimeout("MostrarSecuencia()", duracion[tiempo])
			tiempo++
				if ( tiempo == 5 )
					tiempo = 1
			SecuenciaEjecutandose = true
		}
		
		function IniciarSecuencia() {
			imagen = 1
			MostrarSecuencia()
		}
		
	</script>
	
	<body onload="IniciarSecuencia()">
		<div id="1">
			<p><img src="img/g1.jpg" alt="Secuencia" name="secuencia"></p>
		</div>
		<div id="2" style="position:absolute; top:300;">
			<EMBED src="sound/summer.mp3" autostart="true" loop="true">
		</div>
	</body>
</html>

EJERCICIO 5

Fichero .js
//DECLARACIÓN DE VARIABLES
var SecuenciaID = null
var imagen = 0
var tiempo = 1
var cancion = 0
		
//ARRAY DE IMÁGENES
{imagenes = new CreaArray(4)
imagenes[1].src = "img/g1.jpg"
imagenes[2].src = "img/g2.png"
imagenes[3].src = "img/g3.jpg"
imagenes[4].src = "img/g4.jpg"
}
		
//ARRAY DE "DURACIONES". Tiempo durante el cual se mostrará cada imagen
{duracion = new CreaArray2(4)
duracion[1] = 1000
duracion[2] = 2000
duracion[3] = 3000
duracion[4] = 4000
}
		
//ARRAY DE "TAMAÑOS". Tamaño que irá tomando cada imagen
{size = new CreaArray2(4)
size[1] = 100
size[2] = 200
size[3] = 300
size[4] = 400
}
		
//FUNCIONCES QUE DEBEMOS DEFINIR PARA CREAR LOS ARRAYS
function CreaArray(n) {
	//DEFINIMOS EL TAMAÑO DEL ARRAY
	this.length = n
	for (var i = 1; i<=n; i++) {
		this[i] = new Image()
	}
	return this
}
		
function CreaArray2(n) {
	this.length = n
	for (var i = 1; i<=n; i++) {
		this[i] = 0
	}
	return this
}
		
function MostrarSecuencia () {
	{
	//DEFINIR TAMAÑO DE LAS IMÁGENES
	document.images["secuencia"].width = size[imagen]
	document.images["secuencia"].height = size[imagen]
		
	//A TODAS LAS IMÁGENES DE <body> CUYO NOMBRE SEA "Secuencia"
	//LE ASIGNAMOS LAS DEL ARRAY
	document.images["secuencia"].src = imagenes[imagen].src
	//INCREMENTA EL VALOR DE "imagen" PARA QUE A CADA VUELTA MUESTRE LA
	//SIGUIENTE SI LLEGA AL FINAL, COMIENZA POR LA PRIMERA DE NUEVO.
	imagen ++
		if ( imagen == 5 )
			imagen = 1
	}
				
	cancion = cancion + duracion[tiempo]
			
	if ( cancion <= 60000 ) {
		//setTimeout PERMITE EJECUTAR UNA FUNCIÓN PASADO CIERTO TIEMPO.
		SecuenciaID = setTimeout("MostrarSecuencia()", duracion[tiempo])
			
		tiempo ++
			if ( tiempo == 5 )
				tiempo = 1
	}
}
		
function IniciarSecuencia() {
	imagen = 1
	MostrarSecuencia()
}

Fichero .html
<html>
	<head>
		<script src="js/secuencia.js" language="javascript" type="text/javascript">
		</script>
	</head>

	<body onload="IniciarSecuencia()">
		<p><img src="img/g1.jpg" alt="Secuencia" name="secuencia"></p>
		<EMBED src="sound/summer.mp3" autostart="true" loop="false" hidden="yes">

	</body>
</html>

EJERCICIO 6

Fichero .js
//DECLARACIÓN DE VARIABLES
var SecuenciaID = null
var SecuenciaEjecutandose = null
var imagen = 1
//Inicialmente imagen vale 1 y eliminamos la función IniciarSecuencia
var tiempo = 1
		
//ARRAY DE IMÁGENES
{imagenes = new CreaArray(4)
imagenes[1].src = "img/g1.jpg"
imagenes[2].src = "img/g2.png"
imagenes[3].src = "img/g3.jpg"
imagenes[4].src = "img/g4.jpg"
}
	
//ARRAY DE "DURACIONES". Tiempo durante el cual se mostrará cada imagen
{duracion = new CreaArray2(4)
duracion[1] = 1000
duracion[2] = 2000
duracion[3] = 3000
duracion[4] = 4000
}
		
//ARRAY DE "TAMAÑOS". Tamaño que irá tomando cada imagen
{size = new CreaArray2(4)
size[1] = 100
size[2] = 200
size[3] = 300
size[4] = 400
}
		
//FUNCIONCES QUE DEBEMOS DEFINIR PARA CREAR LOS ARRAYS
function CreaArray(n) {
	//DEFINIMOS EL TAMAÑO DEL ARRAY
	this.length = n
	for (var i = 1; i<=n; i++) {
		this[i] = new Image()
	}
	return this
}
		
function CreaArray2(n) {
	this.length = n
	for (var i = 1; i<=n; i++) {
		this[i] = 0
	}
	return this
}
		
function MostrarSecuencia () {
	if ( SecuenciaEjecutandose == true ) {
		//DEFINIR TAMAÑO DE LAS IMÁGENES
		document.images["secuencia"].width = size[imagen]
		document.images["secuencia"].height = size[imagen]
				
		//A TODAS LAS IMÁGENES DE <body> CUYO NOMBRE SEA "Secuencia"
		//LE ASIGNAMOS LAS DEL ARRAY
		document.images["secuencia"].src = imagenes[imagen].src
		//INCREMENTA EL VALOR DE "imagen" PARA QUE A CADA VUELTA MUESTRE LA
		//SIGUIENTE. SI LLEGA AL FINAL, COMIENZA POR LA PRIMERA DE NUEVO.
		imagen ++
		if ( imagen == 5 )
			imagen = 1
				
	//setTimeout PERMITE EJECUTAR UNA FUNCIÓN PASADO CIERTO TIEMPO.
	SecuenciaID = setTimeout("MostrarSecuencia()", duracion[tiempo])
		
	tiempo ++
	if ( tiempo == 5 )
		tiempo = 1
	}
			
}
		
function Iniciar () {
	SecuenciaEjecutandose = true
	MostrarSecuencia()
}
	
function Parar () {
	SecuenciaEjecutandose = false
	MostrarSecuencia()
}

Fichero .html
<html>
	<head>
		<script src="js/secuenciaConBotones.js" language="javascript" type="text/javascript">
		</script>
	</head>
	
	<body>
		<p><img src="img/g1.jpg" alt="Secuencia" name="secuencia"></p>
		<EMBED src="sound/summer.mp3" autostart="true" loop="true" hidden="yes">
		<input type="button" value="Iniciar secuencia" onClick="Iniciar()" style="position:absolute; left:500; top:50">
		<input type="button" value="Parar secuencia" onClick="Parar()" style="position:absolute; left:500; top:150">
	</body>
</html>

14 comentarios:

  1. muchísimas gracias, me sirvió un montón

    ResponderEliminar
  2. Muchas gracias, tengo una duda se le puede poner link a la imagenes para que te direccione a una url?

    ResponderEliminar
    Respuestas
    1. Hola! Gracias por tu comentario. Creo que no sería muy difícil hacerlo, quizás con document.links http://www.w3schools.com/jsref/coll_doc_links.asp y definiendo en los arrays el enlace de cada imagen...
      Avísame si lo consigues! Si no intentó mirarme cómo hacerlo.

      Saludos :)

      Eliminar
    2. Hola disculpa no haber contestado, busque y busque, y nada puse varias variantes de otros codigo y nada, seria de gran ayuda amigo si pudieras ayudarme, y muchas gracias.

      Eliminar
    3. Hola! Siento no haber contestado antes... Se me ocurre lo siguiente:
      1.- igual que creas el array en javascript con los src de las imágenes, puedes crear uno con los enlaces (de manera que cada enlace esté en la misma posición de su array que la imagen correspondiente en el suyo).
      2.- en el html, pones un enlace a la imagen y le pones un name, por ejemplo, "enlace".
      3.- cuando vas cambiando el src a la imagen, cambias también el href al enlace con el siguiente código: document.links["enlace"].href = posición del array de enlaces creado que toque.

      Sería más sencillo con jQuery, pero la gracia de este ejercicio era utilizar únicamente JavaScript.

      Eliminar
  3. Muy bueno ; no se como hacer para avanzar o retroceder imagenes segun el scrol del mouse

    ResponderEliminar
    Respuestas
    1. Hola! Creo que esto podría ayudarte https://developer.mozilla.org/en-US/docs/Web/API/window.onscroll

      Eliminar
  4. Excelente ! Muchas Gracias :D ! Eres lo máximo :3

    ResponderEliminar
  5. Muchas gracias por tu aportación me ha sido muy útil!!

    ResponderEliminar
  6. salvaste mi vida.. No te imaginas como me ha servido Gracias!!! :*

    ResponderEliminar
  7. Hola!

    Muchisimas gracias por publicarlo, el que me sirvo para mi proyecto es el ejercicio 2.

    ResponderEliminar