Animasi DOM JavaScript HTML
Belajar membuat animasi HTML menggunakan JavaScript.
Halaman Web Dasar
Untuk mendemonstrasikan cara membuat animasi HTML dengan JavaScript, kita akan menggunakan halaman web sederhana:
Contoh
<!DOCTYPE html>
<html>
<body>
<h1>My First
JavaScript Animation</h1>
<div id="animation">My animation will go here</div>
</body>
</html>
Buat Wadah Animasi
Semua animasi harus relatif terhadap elemen penampung.
Contoh
<div id ="container">
<div id ="animate">My
animation will go here</div>
</div>
Gaya Elemen
Elemen container harus dibuat dengan style = " position: relative
".
Elemen animasi harus dibuat dengan style = " position: absolute
".
Contoh
#container {
width: 400px;
height:
400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height:
50px;
position: absolute;
background: red;
}
Kode Animasi
Animasi JavaScript dilakukan dengan memprogram perubahan bertahap dalam gaya elemen.
Perubahan tersebut disebut dengan timer. Ketika interval timer kecil, animasi terlihat terus menerus.
Kode dasarnya adalah:
Contoh
id = setInterval(frame, 5);
function frame() {
if (/*
test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}
Buat Animasi Penuh Menggunakan JavaScript
Contoh
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';
}
}
}