鍍金池/ 問答/室內(nèi)設計/ svg中怎么獲得鼠標指針的相對位置

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

回答
編輯回答
乞許

你得對一個不變的元素進行鼠標事件監(jiān)聽,不然不亂套了

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>
2017年8月22日 23:49