โœจcat behind hat

JS โŸฉ browser โŸฉ animation โŸฉ example โŸฉ 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