Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

วิธีใช้ CSS Animations หมุนรูปภาพต่อเนื่อง

Quick tutorial: เรียนรู้หมุนรูปภาพต่อเนื่องด้วย CSS animation property

HTML markup พร้อม image และ attributes:

<img src="https://th.wsxdn.com/UploadFiles_2907/202203/2022033109325250.png" class="rotate linear infinite" width="150" height="150" />

Image ควรแสดงแบบนี้:

วิธีใช้ CSS Animations หมุนรูปภาพต่อเนื่อง

Image element มี 3 classes: rotate, linear และ infinite ใน CSS stylesheet ต้องสร้าง declaration block สำหรับแต่ละ class เรียกว่า utility หรือ helper classes แต่ชอบ single-purpose เพราะ descriptive มากกว่า

Declare .rotate code block:

.rotate { animation: rotation 2s; }

ยังไมเกิดอะไร ต้อง define animation property's rotation function เพิ่ม CSS keyframe rule:

@keyframes rotation { from { transform: rotate(0deg); } to { transform: rotate(359deg); } }

Reload browser tab ควรเห็น image หมุนรอบเดียว 2 วินาที (2s) แตะต้องทำอีก 2 อย่าง: ทำให้หมุนต่อเนื่อง และเปลี่ยน animation timing จาก default ease เป็น consistent speed curve linear

เพิ่ม .linear declaration block:

.linear { animation-timing-function: linear; }

Reload browser tab image หมุนที่ความเร็วคงที่ start to end

สุดท้าย ทำให้หมุน infinitely declare .infinite class code block:

.infinite { animation-iteration-count: infinite; }

Voila! Infinitely/continuously spinning image ด้วย linear animation speed curve

วิธีใช้ CSS Animations หมุนรูปภาพต่อเนื่อง

ดู complete code ที่ CodePen

หมายเหตุ: declare ทุก animation properties ใน single line และ single class ได้:

.rotate-image { animation: rotation 2s linear infinite; }

Code ข้างต้นประหยัดมาก แตะสำหรับ learning/teaching ชอบ break down smaller bites เพราะเข้าใจง่ายกว่า individual components ทำงานร่วมกัน

Animation curves อื่นๆ มากกว่า default ease และ linear ที่ใช้ cubic-bezier animation curve ได้ fancy มาก แต่เก็บไว้ tutorial อื่น