โจcat behind hat
JS โฉ browser โฉ animation โฉ example โฉ moving cat
move image by updating its .style.tranform
property.
replit โฉ cat behind hat
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 = '';
};
window.requestAnimateFrame() โญ๏ธ
Last updated