แอนิเมชั่นด้วยตนเอง
ภายใต้แอนิเมชั่นแบบแมนนวล กระบวนการแอนิเมชั่นจะไม่เป็นแบบอัตโนมัติ ต่อไปนี้คือการใช้งานแอนิเมชั่นอย่างง่ายโดยใช้คุณสมบัติของวัตถุ DOM และฟังก์ชัน JavaScript ดังนี้ รายการต่อไปนี้มีวิธี DOM ที่แตกต่างกัน
- เรากำลังใช้ฟังก์ชัน JavaScript getElementById() เพื่อรับวัตถุ DOM แล้วกำหนดให้กับตัวแปรโกลบอล imgObj
- เราได้กำหนดฟังก์ชันการเริ่มต้น init() เพื่อเริ่มต้น imgObj โดยเราได้กำหนดตำแหน่งและคุณลักษณะด้านซ้ายไว้
- เรากำลังเรียกใช้ฟังก์ชันการเริ่มต้นในขณะที่โหลดหน้าต่าง
- สุดท้าย เรากำลังเรียก moveRight() ฟังก์ชั่นเพิ่มระยะห่างด้านซ้าย 10 พิกเซล คุณยังตั้งค่าเป็นค่าลบเพื่อเลื่อนไปทางด้านซ้ายได้อีกด้วย
ตัวอย่าง
คุณสามารถลองเรียกใช้โค้ดต่อไปนี้เพื่อใช้งานแอนิเมชั่นใน JavaScript
<html>
<head>
<title>JavaScript Animation</title>
<script>
<!--
var imgObj = null;
function init() {
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight() {
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
}
window.onload =init;
//-->
</script>
</head>
<body>
<form>
<img id="myImage" src="/images/html.gif" />
<p>Click button below to move the image to right</p>
<input type = "button" value = "Click Me" onclick = "moveRight();" />
</form>
</body>
</html> แอนิเมชั่นอัตโนมัติ
เราสามารถทำให้กระบวนการนี้เป็นไปโดยอัตโนมัติโดยใช้ฟังก์ชัน JavaScript setTimeout() ดังนี้ −
เราได้เพิ่มวิธีการเพิ่มเติมที่นี่ มาดูกันว่ามีอะไรใหม่บ้าง -
- The moveRight() ฟังก์ชันกำลังเรียก setTimeout() ฟังก์ชั่นกำหนดตำแหน่งของ imgObj.
- เราได้เพิ่มฟังก์ชันใหม่ stop() เพื่อล้างตัวจับเวลาที่กำหนดโดย setTimeout() ฟังก์ชันและกำหนดให้วัตถุอยู่ที่ตำแหน่งเริ่มต้น
ตัวอย่าง
คุณสามารถลองเรียกใช้โค้ดต่อไปนี้เพื่อใช้งาน Automated Animation ใน JavaScript -
<html>
<head>
<title>JavaScript Animation</title>
<script>
<!--
var imgObj = null;
var animate ;
function init() {
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight() {
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
}
function stop(){
clearTimeout(animate);
imgObj.style.left = '0px';
}
window.onload =init;
//-->
</script>
</head>
<body>
<form>
<img id="myImage" src="/images/html.gif" />
<p>Click the buttons below to handle animation</p>
<input type = "button" value = "Start" onclick = "moveRight();" />
<input type = "button" value = "Stop" onclick = "stop();" />
</form>
</body>
</html>