เรียนรู้การสร้างภาพเคลื่อนไหว 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="ตำแหน่ง: สัมพันธ์
"
องค์ประกอบภาพเคลื่อนไหวควรถูกสร้างขึ้นด้วย style="ตำแหน่ง: สัมบูรณ์
"
#container {
width: 400px;
height:
400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height:
50px;
position: absolute;
background: red;
}
ลองด้วยตัวคุณเอง →
<!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>
ภาพเคลื่อนไหว JavaScript ทำได้โดยการเขียนโปรแกรมการเปลี่ยนแปลงทีละน้อยในองค์ประกอบ สไตล์.
การเปลี่ยนแปลงจะถูกเรียกโดยตัวจับเวลา เมื่อช่วงเวลาของตัวจับเวลาน้อย แอนิเมชั่นดูต่อเนื่อง
รหัสพื้นฐานคือ:
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';
}
}
}
ลองด้วยตัวคุณเอง →
<!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>