How to get the relative position of mouse pointer in svg

draw a 1000-wide rectangle with svg. I want to get the relative position of the pointer in the rectangle when the mouse moves. How should I write it?

for example, move horizontally to the middle, and x is 500. The code is as follows:

  http://jsrun.net/kdgKp/edit

Svg
Apr.05,2021

you have to listen for mouse events on an immutable element, otherwise you won't mess up

function handleMouseMove(event) {
  // console.log(evt)
  const width = document.getElementById('container').scrollWidth;
  const offsetX = event.offsetX


  console.log(width,offsetX,event)
  document.getElementById('rect').setAttribute('x',offsetX/width*1000)
  // const im = evt.target.getScreenCTM();
  // const svg = evt.target.ownerSVGElement;
  // const pt = svg.createSVGPoint();
  // pt.x = evt.clientX;
  // pt.y = evt.clientY;
  // const p = pt.matrixTransform(im);
  // console.log(p.x, p.y);
}
<svg version="1.1" baseProfile="full" width="100%" height="200" viewBox="0 0 1020 200"
xmlns="http://www.w3.org/2000/svg" style="border: 1px solid red" id="container" onmousemove="handleMouseMove(event)">
  <g transform="translate(10,0)">
    <rect id="rect" x="0" width="1000" height="90%" fill="-sharp33546F"/>
    <line x1="100" x2="100" y1="0" y2="90%" stroke="-sharpccc" id="line" />
  </g>
</svg>
Menu