Animación DOM de JavaScript


Tabla de contenido

    Mostrar tabla de contenidos


Aprenda a crear animaciones HTML usando JavaScript.


Una página web básica

Para demostrar cómo crear animaciones HTML con JavaScript, usaremos un sencillo Página web:

Ejemplo

<!DOCTYPE html>
<html>
<body>
<h1>My First 
 JavaScript Animation</h1>

<div id="animation">My animation will go here</div>

</body>
</html>

Crear un contenedor de animación

Todas las animaciones deben ser relativas a un elemento contenedor.

Ejemplo

<div id ="container">
  <div id ="animate">My 
 animation will go here</div>
</div>

Diseñar los elementos

El elemento contenedor debe crearse con estilo="posición: relativa".

El elemento de animación debe crearse con estilo="posición: absoluta".

Ejemplo

#container {
  width: 400px;
  height: 
 400px;
  position: relative;
  
 background: yellow;
 }
#animate {
  width: 50px;
  height: 
 50px;
  position: absolute;
  
 background: red;
}

Pruébelo usted mismo →

<!Doctype html>
<html>
<style>
#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: yellow;
}
#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background: red;
}
</style>
<body>

<h2>My First JavaScript Animation</h2>

<div id="container">
<div id="animate"></div>
</div>

</body>
</html>


Código de animación

Las animaciones de JavaScript se realizan programando cambios graduales en un elemento. estilo.

Los cambios son llamados por un temporizador. Cuando el intervalo del temporizador es pequeño, el la animación parece continua.

El código básico es:

Ejemplo

id = setInterval(frame, 5);
function frame() {
  if (/* 
 test for finished */) {
    clearInterval(id);
  } else {
      
 /* code to change the element style */  
  }
}

Crea la animación completa usando JavaScript

Ejemplo

function myMove() {
  let id = null;
  const elem = document.getElementById("animate");
  let pos = 0;
  
  clearInterval(id);
  id = setInterval(frame, 5);
  
 function frame() {
    if (pos == 
 350) {
      
 clearInterval(id);
    } else {
      
 pos++; 
      elem.style.top = pos + 'px'; 
      elem.style.left = pos + 'px'; 
      }
  }
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<style>
#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: yellow;
}
#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: red;
}
</style>
<body>

<p><button onclick="myMove()">Click Me</button></p> 

<div id ="container">
  <div id ="animate"></div>
</div>

<script>
function myMove() {
  let id = null;
  const elem = document.getElementById("animate");   
  let pos = 0;
  clearInterval(id);
  id = setInterval(frame, 5);
  function frame() {
    if (pos == 350) {
      clearInterval(id);
    } else {
      pos++; 
      elem.style.top = pos + "px"; 
      elem.style.left = pos + "px"; 
    }
  }
}
</script>

</body>
</html>