# cat in hat

[JS](../../../js) ⟩ [browser](../..) ⟩ [animation](..) ⟩ [example]() ⟩ 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](../../dom/type/window/.requestanimationframe "mention")
{% endtab %}

{% tab title="📗 參考" %}
* [ ] Eloquent JS ⟩ DOM ⟩ [Positioning & Animating](https://eloquentjavascript.net/14_dom.html#h_MAsyozbjjZ)
{% endtab %}
{% endtabs %}

