Aprenda a crear animaciones HTML usando JavaScript.
Para demostrar cómo crear animaciones HTML con JavaScript, usaremos un sencillo Página web:
<!DOCTYPE html>
<html>
<body>
<h1>My First
JavaScript Animation</h1>
<div id="animation">My animation will go here</div>
</body>
</html>
Todas las animaciones deben ser relativas a un elemento contenedor.
<div id ="container">
<div id ="animate">My
animation will go here</div>
</div>
El elemento contenedor debe crearse con estilo="posición: relativa
".
El elemento de animación debe crearse con estilo="posición: absoluta
".
#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>
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:
id = setInterval(frame, 5);
function frame() {
if (/*
test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}
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>