Click Start to move the image downward and then toward the right. Reset stops the animation and restores the initial position.
const image = document.getElementById('i1');
const area = document.getElementById('move-area');
const output = document.getElementById('msg');
const startButton = document.getElementById('start');
const resetButton = document.getElementById('reset');
let animationId = null;
function draw() {
const maxTop = Math.max(0, area.clientHeight - image.offsetHeight);
const maxLeft = Math.max(0, area.clientWidth - image.offsetWidth);
let top = image.offsetTop;
let left = image.offsetLeft;
if (top < maxTop) top = Math.min(maxTop, top + 2);
else if (left < maxLeft) left = Math.min(maxLeft, left + 2);
else { animationId = null; return; }
image.style.top = `${top}px`;
image.style.left = `${left}px`;
output.textContent = `X: ${left} Y: ${top}`;
animationId = requestAnimationFrame(draw);
}
function start() { if (animationId === null) animationId = requestAnimationFrame(draw); }
function reset() {
if (animationId !== null) cancelAnimationFrame(animationId);
animationId = null; image.style.left='40px'; image.style.top='40px'; output.textContent='';
}
startButton.addEventListener('click', start);
resetButton.addEventListener('click', reset);
<div id="move-area" class="border rounded mb-3" style="position:relative; min-height:420px; overflow:hidden; touch-action:none;">
<img src="images/help.jpg" id="i1" alt="Help icon used in JavaScript image movement demo" style="position:absolute; left:40px; top:40px; max-width:80px; height:auto;">
</div>
<button type="button" id="start">Start</button>
<button type="button" id="reset">Reset</button>
<div id="msg"></div>