JavaScript HTML DOM นิเมชั่น
เรียนรู้การสร้างภาพเคลื่อนไหว HTML โดยใช้ JavaScript
หน้าเว็บพื้นฐาน
เพื่อสาธิตวิธีสร้างภาพเคลื่อนไหว HTML ด้วย JavaScript เราจะใช้หน้าเว็บอย่างง่าย:
ตัวอย่าง
<!DOCTYPE html>
<html>
<body>
<h1>My First
JavaScript Animation</h1>
<div id="animation">My animation will go here</div>
</body>
</html>
สร้างคอนเทนเนอร์แอนิเมชั่น
ภาพเคลื่อนไหวทั้งหมดควรสัมพันธ์กับองค์ประกอบคอนเทนเนอร์
ตัวอย่าง
<div id ="container">
<div id ="animate">My
animation will go here</div>
</div>
จัดรูปแบบองค์ประกอบ
ควรสร้างองค์ประกอบคอนเทนเนอร์ด้วย style = " position: relative
"
องค์ประกอบแอนิเมชั่นควรสร้างด้วย style = " position: absolute
"
ตัวอย่าง
#container {
width: 400px;
height:
400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height:
50px;
position: absolute;
background: red;
}
รหัสแอนิเมชั่น
แอนิเมชั่น JavaScript ทำได้โดยการเขียนโปรแกรมการเปลี่ยนแปลงทีละน้อยในสไตล์ขององค์ประกอบ
การเปลี่ยนแปลงจะถูกเรียกโดยตัวจับเวลา เมื่อตัวจับเวลามีน้อย ภาพเคลื่อนไหวจะดูต่อเนื่อง
รหัสพื้นฐานคือ:
ตัวอย่าง
id = setInterval(frame, 5);
function frame() {
if (/*
test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}
สร้างแอนิเมชั่นแบบเต็มโดยใช้ JavaScript
ตัวอย่าง
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';
}
}
}