首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

HTML/JavaScript 圖片軌跡動畫:從左上角移動到右下再右上再左下

     編輯:程式設計綜合問答

CSS Animation 方案 (推薦、效能佳)

<style>
@keyframes movePath {
    0%   { left: 0;   top: 0; }
    25%  { left: 100%; top: 100%; transform: translate(-100%, -100%); }
    50%  { left: 100%; top: 0;   transform: translate(-100%, 0); }
    75%  { left: 0;   top: 100%; transform: translate(0, -100%); }
    100% { left: 0;   top: 0; }
}
#myImg {
    position: absolute;
    width: 100px; height: 100px;
    animation: movePath 8s linear infinite;
}
</style>

<img id="myImg" src="pic.jpg" alt="動畫圖片">

JavaScript 方案 (彈性控制)

const img = document.getElementById('myImg');
const path = [
    {x: 0, y: 0},
    {x: window.innerWidth - img.width, y: window.innerHeight - img.height},
    {x: window.innerWidth - img.width, y: 0},
    {x: 0, y: window.innerHeight - img.height},
    {x: 0, y: 0}
];
let idx = 0;
function animate() {
    if (idx >= path.length - 1) { idx = 0; }
    const start = path[idx], end = path[idx + 1];
    const duration = 2000; // ms
    const startTime = performance.now();
    function step(now) {
        const t = Math.min((now - startTime) / duration, 1);
        img.style.left = start.x + (end.x - start.x) * t + 'px';
        img.style.top = start.y + (end.y - start.y) * t + 'px';
        if (t < 1) requestAnimationFrame(step);
        else { idx++; animate(); }
    }
    requestAnimationFrame(step);
}
img.style.position = 'absolute';
animate();

Canvas 方案 (高效能、大量精靈)

用 `requestAnimationFrame` 繪製 `drawImage`,邏輯同 JS 方案但繪製在 Canvas 上,避免 DOM 重排。

選擇建議

  • 單圖片、固定路徑 → **CSS @keyframes** 最簡潔、GPU 加速。
  • 路徑動態計算、互動控制 → **JS requestAnimationFrame**。
  • 遊戲/大量動畫 → **Canvas/WebGL**。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved