cat in hat

JSbrowseranimationexample ⟩ moving cat

keep images moving by updating their .style.left/top properties.

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));
}

Last updated