coords

by aio350

HTML

<canvas width="300" height="300" style="border: 1px dotted #222"></canvas>

CSS

body {
  margin: 0;
  height: 100vh;
  background: radial-gradient(circle, skyblue, steelblue);
  display: flex;
  justify-content: center;
  align-items: center;
}

JavaScript

const canvas = document.querySelector('canvas')
const $ = canvas.getContext('2d')

function writeMsg(canvas, msg) {
  $.clearRect(0, 0, canvas.width, canvas.height)
  $.font = '14pt Calibri'
  $.fillStyle = '#222'
  $.fillText(msg, 10, 25)
}

function getPos(canvas, e) {
  let rect = canvas.getBoundingClientRect()
  return {
    x: Math.round(e.clientX - rect.left),
    y: Math.round(e.clientY - rect.top)
  }
}

canvas.addEventListener('mousemove', (e) => {
  let pos = getPos(canvas, e)
  let msg = `Mouse position: x: ${pos.x}, y: ${pos.y}`
  writeMsg(canvas, msg)
})

canvas.addEventListener('mouseout', () => $.clearRect(0, 0, canvas.width, canvas.height))