Demo of Image moving around all four sides of the browser area

The original Start and Stop controls are preserved. The modern version follows the four sides of a responsive demo area rather than using screen.width/screen.height, which do not describe the page content area.

Help icon used in JavaScript image movement demo
Return to tutorial on Moving image across screen Moving image vertically within two boundaries Moving image horizontally within two boundaries Moving image randomly within four boundaries Moving image by using up, down, left & right keys

JavaScript source

const image = document.getElementById('i1');
const area = document.getElementById('move-area');
const output = document.getElementById('msg');
const startButton = document.getElementById('start');
const stopButton = document.getElementById('stop');
let animationId = null;
let side = 0;
const step = 2;

function draw() {
  const maxLeft = Math.max(0, area.clientWidth - image.offsetWidth);
  const maxTop = Math.max(0, area.clientHeight - image.offsetHeight);
  let left = image.offsetLeft;
  let top = image.offsetTop;

  if (side === 0) { left = Math.min(maxLeft, left + step); if (left >= maxLeft) side = 1; }
  else if (side === 1) { top = Math.min(maxTop, top + step); if (top >= maxTop) side = 2; }
  else if (side === 2) { left = Math.max(0, left - step); if (left <= 0) side = 3; }
  else { top = Math.max(0, top - step); if (top <= 0) side = 0; }

  image.style.left = `${left}px`;
  image.style.top = `${top}px`;
  output.textContent = `X: ${left} Y: ${top}`;
  animationId = requestAnimationFrame(draw);
}
function start() {
  if (animationId !== null) return;
  image.style.left = '0px'; image.style.top = '0px'; side = 0;
  animationId = requestAnimationFrame(draw);
}
function stop() {
  if (animationId !== null) cancelAnimationFrame(animationId);
  animationId = null;
  output.textContent = '';
}
startButton.addEventListener('click', start);
stopButton.addEventListener('click', stop);

HTML source

<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:0px; top:0px; max-width:80px; height:auto;">
</div>
<button type="button" id="start">Start</button>
<button type="button" id="stop">Stop</button>
<div id="msg"></div>