cat behind hat

JSbrowseranimationexample ⟩ moving cat

move image by updating its .style.tranform property.

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 = '';
};

Last updated