我想找到鼠标点击相对于SVG元素的X,Y位置。 SVG元素将嵌入到HTML中。
null
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>
null
在控制台中打印X和Y之前,想要对SVG的offsetLeft和offsetTop进行子间隔。 但无法获得这些值
若要获取元素坐标或大小,请使用element.GetBoundingClientRect
event.Target.GetBoundingClientRect()
或event.CurrentTarget.GetBoundingClientRect()
(用于绑定到侦听器的元素,而不是传播事件的元素)。 或者直接使用缓存的元素引用常量svg.GetBoundingClientRect()
const bcr = event.target.getBoundingClientRect();
console.log(bcr.left, bcr.top)
https://developer.mozilla.org/en-us/docs/web/api/element/GetBoundingClientRect
在您的特定情况下,要获得相对的鼠标坐标:
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);
});
您可以得到相对于元素的坐标,如下所示:
null
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>