<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="動畫圖片">
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();
用 `requestAnimationFrame` 繪製 `drawImage`,邏輯同 JS 方案但繪製在 Canvas 上,避免 DOM 重排。