ทำ animation บนเว็บไซต์ด้วยคำสั่ง css animation ไม่ยากอย่างที่คิด


🕑 18 ก.ค. 2561
ทำ animation บนเว็บไซต์ด้วยคำสั่ง css animation ไม่ยากอย่างที่คิด

การทำ animation บนเว็บไซต์แบบง่ายๆด้วยคำสั่ง css animation แบบเจาะลึกกันครับ

ในการทำ animation ด้วยคำสั่ง css animation ปัจจุบันนิยมเขียนด้วย css version 3 หรือ css3 น่ะครับ

รูปแบบคำสั่งและการใช้งาน animation

ใส่ animation-name ซึ่ง animation-name จะไปเรียกการใช้งาน properties ต่างๆจากใน animation keyframe

property ที่ใช้สำหรับกำหนดค่า animation  ใน css

/*
animation-name : การตั้งชื่อ animation เพื่อนำไปใช้กำหนดในคำสั่ง keyframe
animation-duration: คือเวลาที่จะแสดงผล animation ใน 1 รอบ
animation-timing-function: คือเวลาที่ใช้หน่วงตอนแสดงผลให้เร็วช้าไม่เท่ากันเพื่อเพิ่มความสวยงามตอนแสดง animation
animation-delay: คือเวลาหน่วงก่อนแสดงผล animation
animation-iteration-count: คือจำนวนรอบที่ให้แสดงผล
animation-direction: คือทิศทางที่จะให้ animation แสดงผล
animation-fill-mode :
animation-play-state: ใช้สำหรับให้ animation แสดงผล หรือ หยุดแสดงผล
*/

สามารถใช้รูปย่อได้ดังนี้

animation: example 5s linear 2s infinite alternate;
 

คำสั่ง keyframe

from
A starting offset of 0%.
to
An ending offset of 100%.

หลักการทำงานของ keyframe เราสามารถกำหนด การทำงาน ของ property ใน แต่ละส่วนของ keyframe โดยใช่หน่วยเป็น % 

@keyframes slidein {
  from {
    margin-left: 100%;
    width: 300%;
  }

  to {
    margin-left: 0%;
    width: 100%;
  }
}

ตัวอย่าง กำนหนดให้ div เคลื่อนที่จากซ้ายไปขวา

ลิงค์ตัวอย่างผลลัพธ์การแสดงผล https://www.w3schools.com/cssref/tryit.asp?filename=trycss3_animation

<!DOCTYPE html>
<html>
<head>
<style> 
div {
    width: 100px;
    height: 100px;
    background: red;
    position: relative;
    -webkit-animation-name: mymove; /* Safari 4.0 - 8.0 */
    -webkit-animation-duration: 5s; /* Safari 4.0 - 8.0 */
    animation-name: mymove;
    animation-duration: 5s;
}

/* Safari 4.0 - 8.0 */
@-webkit-keyframes mymove {
    from {left: 0px;}
    to {left: 200px;}
}

@keyframes mymove {
    from {left: 0px;}
    to {left: 200px;}
}
</style>
</head>
<body>
  <div></div>
</body>
</html>

 

ตัวอย่างการทำ loading animation ลองเข้าไปศึกษาตัวอย่างการเขียนโค้ดได้ครับ

See the Pen CSS3 Loading animations by Manoz (@Manoz) on CodePen.

 

บทความหน้าจะมาแนะนำการทำ animation บนเว็บไซต์ด้วย SVG กันครับ

เทพควิช-lnwquiz