> 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-in-hat.md).

# cat in 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" %}
keep images moving by updating their <mark style="color:yellow;">`.style.left/top`</mark> properties.
{% endhint %}

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

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

```javascript
const {log} = console;
const {cos, sin} = Math;

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

let cat = $("#cat");
let hat = $("#hat");

let angle = 0;

// 1. request first frame
requestAnimationFrame(animate);

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

    if (!t0) t0 = t1;
    
    // 2. update animation
    angle += (t1 - t0) * 0.001;            // 57.3 °/sec
    const r = 100 * (1 + cos(4*angle));
    const [x, y] = [r * cos(angle) + 160, r * sin(angle) + 200]
    
    cat.style.left = x + "px";
    cat.style.top = y + "px";

    hat.style.left = (x - 25) + "px";
    hat.style.top = (y - 40) + "px";
    
    // 3. request next frame
    requestAnimationFrame(t2 => animate(t2, t1));
}
```

{% endtab %}

{% tab title="🗺️ 圖表" %}
{% embed url="<https://replit.com/@pegasusroe/animation-cat-in-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 %}
  {% endtabs %}
