简体   繁体   中英

Get X,Y position of element in Javascript

I want to find X,Y position of mouse click relative to SVG element. The SVG element will be embedded in HTML.

 var svg = document.getElementById("svg1"); svg.addEventListener('click', event => { let x = event.clientX; let y = event.clientY; console.log(x, y); });
 html { height: 100% } body { height: 100%; display: flex; justify-content: center; background-color: #fff; } svg { height: 100%; background: grey; }
 <svg id="svg1" viewBox="0 0 100 100"> <circle cx="50" cy="50" r="40" fill="#52c927" /> <circle cx="50" cy="50" r="25" fill="white" /> <circle cx="50" cy="50" r="15" fill="red" /> </svg>

Want to subract offsetLeft and offsetTop of SVG before printing X and Y in console. But not able to get those value

To get an element coordinates or size use Element.getBoundingClientRect

event.target.getBoundingClientRect() or event.currentTarget.getBoundingClientRect() (for the element bound to the listener, rather than the one who propagated the event). Or directly with your cached Element reference constant svg.getBoundingClientRect()

const bcr = event.target.getBoundingClientRect();
console.log(bcr.left, bcr.top)

https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

In your specific case, to get the relative mouse coordinates:

var svg = document.getElementById("svg1");
svg.addEventListener('click', event => {
  const bcr = event.target.getBoundingClientRect();
  const relative_x = event.clientX - bcr.left;
  const relative_y = event.clientY - bcr.top;
  console.log(relative_x, relative_y);
});

You can get the coordinates relative to the element like this:

 var svg = document.getElementById("svg1"); svg.addEventListener('click', event => { const rect = svg.getBoundingClientRect(); let x = event.clientX - rect.left; let y = event.clientY - rect.top; console.log(x, y); });
 html { height: 100% } body { height: 100%; display: flex; justify-content: center; background-color: #fff; } svg { height: 100%; background: grey; }
 <svg id="svg1" viewBox="0 0 100 100"> <circle cx="50" cy="50" r="40" fill="#52c927" /> <circle cx="50" cy="50" r="25" fill="white" /> <circle cx="50" cy="50" r="15" fill="red" /> </svg>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM