> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/browser/anim/ex/cat-behind-hat.md).

# cat behind hat

[JS](/web/js.md) ⟩ [browser](/web/browser.md) ⟩ [animation](/web/browser/anim.md) ⟩ [example](/web/browser/anim/ex.md) ⟩ moving cat

{% hint style="success" %}
move image by updating its <mark style="color:yellow;">`.style.tranform`</mark> property.
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}

* replit ⟩ [cat behind hat](https://replit.com/@pegasusroe/cat-behind-hat#index.js)

```javascript
const {log} = console

// ⭐️ import
import { $ } from './js/ext/Node_ext.js'; // Node extension
// --------------------------------------------------------------------

// ⭐️ absolutely positioned <img>
const hat = $('#hat');

// ⭐️ animation parameters
let x = 0;            // current translation (in px)
const LIMIT = 200;    // translation limit
const SPEED = 0.1;    // 100 px/sec = 0.1 px/ms

// ⭐️ render loop
// -------------------------------------------------------
// - t1: current timestamp
// - t0: last timestamp
function animate(t1, t0) {

    // ⭐️ setup/log starting timestamp
    if (!t0) {
        t0 = t1;
        log("first timestamp:", t1);
    };
    
    // ⭐️ update animation parameters
    x += SPEED * (t1 - t0);
    if (x > LIMIT) x = LIMIT;
    
    hat.style.transform = `translateX(${x}px)`;

    // ⭐️ request next frame if not done.
    if (x < LIMIT) {
        requestAnimationFrame(t2 => animate(t2, t1));
    }
}

// ⭐️ event handlers
// -------------------------------------------------------

// "animate" <button>
$('#animate').onclick = function() {
    // request 1st frame
    window.requestAnimationFrame(animate);
};

// "reset" <button>
$('#reset').onclick = function() {
    x = 0;
    hat.style.transform = '';
};
```

{% endtab %}

{% tab title="🗺️ 圖表" %}
{% embed url="<https://replit.com/@pegasusroe/cat-behind-hat#index.js>" %}
{% endtab %}

{% tab title="👥 相關" %}

* [.requestAnimationFrame()](/web/browser/dom/type/window/.requestanimationframe.md)
  {% endtab %}

{% tab title="📗 參考" %}

* [ ] Eloquent JS ⟩ DOM ⟩ [Positioning & Animating](https://eloquentjavascript.net/14_dom.html#h_MAsyozbjjZ)
  {% endtab %}

{% tab title="📘 手冊" %}

* [window.requestAnimateFrame()](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame#examples) ⭐️&#x20;
  {% endtab %}
  {% endtabs %}
