เรียนรู้วิธีการสร้างภาพเคลื่อนไหวโดยใช้ JavaScript
หน้าเว็บพื้นฐาน
แสดงให้เห็นถึงวิธีการสร้างภาพเคลื่อนไหวด้วย JavaScript HTML เราสามารถใช้หน้าเว็บง่าย
ตัวอย่าง
<!DOCTYPE html>
<html>
<body>
<h1>My First
JavaScript Animation</h1>
<div id ="myContainer">
<div id ="myAnimation">My
animation will go here</div>
</div>
</body>
<html>
ลองตัวเอง» จัดแต่งทรงผมองค์ประกอบ
ที่จะทำให้การเคลื่อนไหวเป็นไปได้องค์ประกอบภาพเคลื่อนไหวจะต้องมีการเคลื่อนไหวเทียบกับ "parent container"
องค์ประกอบภาชนะควรได้รับการสร้างขึ้นด้วยลักษณะ = "position: relative"
องค์ประกอบภาพเคลื่อนไหวควรจะสร้างขึ้นด้วยลักษณะ = "position: absolute"
ตัวอย่าง
#myContainer {
width: 400px;
height:
400px;
position: relative;
background: yellow;
}
#myAnimation {
width: 50px;
height:
50px;
position: absolute;
background: red;
}
ลองตัวเอง» รหัสนิเมชั่น
ภาพเคลื่อนไหว JavaScript จะทำโดยการเขียนโปรแกรมเปลี่ยนแปลงอย่างค่อยเป็นค่อยไปในรูปแบบขององค์ประกอบ
การเปลี่ยนแปลงจะถูกเรียกโดยจับเวลา เมื่อช่วงจับเวลาที่มีขนาดเล็ก, ภาพเคลื่อนไหวที่มีลักษณะต่อเนื่อง
รหัสพื้นฐานคือ:
ตัวอย่าง
var id = setInterval(frame, 5);
function frame() {
if (/*
test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}
สร้างภาพเคลื่อนไหวโดยใช้ JavaScript
ตัวอย่าง
function myMove() {
var elem =
document.getElementById("myAnimation");
var pos = 0;
var id = setInterval(frame,
10);
function frame() {
if (pos ==
350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
ลองตัวเอง»