Impara a creare animazioni HTML usando JavaScript.
Una base pagina Web
Per dimostrare come creare animazioni HTML con JavaScript, useremo una semplice pagina web:
Esempio
<!DOCTYPE html>
<html>
<body>
<h1>My First
JavaScript Animation</h1>
<div id="animation">My animation will go here</div>
</body>
</html>
Prova tu stesso " Creare un contenitore di animazione
Tutte le animazioni dovrebbero essere relativi ad un elemento contenitore.
Esempio
<div id ="container">
<div id ="animate">My
animation will go here</div>
</div>
Lo stile Elementi
L'elemento contenitore deve essere creato con style = "position: relative".
L'elemento di animazione dovrebbe essere creato con style = "position: absolute".
Esempio
#container {
width: 400px;
height:
400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height:
50px;
position: absolute;
background: red;
}
Prova tu stesso " codice di animazione
animazioni JavaScript sono fatte programmando graduali cambiamenti nello stile di un elemento.
I cambiamenti sono chiamati da un timer. Quando l'intervallo del timer è piccola, l'animazione è continua.
Il codice di base è:
Esempio
var id = setInterval(frame, 5);
function frame() {
if (/*
test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}
Creare l'animazione utilizzando JavaScript
Esempio
function myMove() {
var elem =
document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos ==
350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
Prova tu stesso "