svg中怎么获得鼠标指针的相对位置

用svg画了一个1000宽度的矩形, 我想鼠标移动时获得指针在矩形中的相对位置,请问要怎么编写?

比如水平移动到中间, x就是500这样子, 代码如下:

<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">
  <g transform="translate(10,0)">
    <rect x="0" width="1000" height="90%" fill="#33546F" onMouseMove="handleMouseMove(evt)" />
    <line x1="100" x2="100" y1="0" y2="90%" stroke="#ccc" id="line" />
  </g>
</svg>

测试代码地址
http://jsrun.net/kdgKp/edit

阅读 4.6k
1 个回答

你得对一个不变的元素进行鼠标事件监听,不然不乱套了

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="#33546F"/>
    <line x1="100" x2="100" y1="0" y2="90%" stroke="#ccc" id="line" />
  </g>
</svg>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进