我有一个 div 块:
<div id="container"></div>
在这个带有 SVG 圆圈的块内有一个 SVG 路径。当我点击时,我得到了 id="container"
的相对坐标。左上角是 0,0。
SVG 元素始终是容器的全宽、高度。但是 SVG 有自己的视口。
如何将 SVG 圆 (x,y) 的所有点重新计算为 #container 的相对坐标?
<div id="container">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2000 1000" width="2000px" height="1000px">
<circle cx="100" cy="100" r="10" fill="#4285f4"></circle>
</svg>
</div>
我需要知道每个圆相对于父 div
的相对坐标。
JavaScript 点击是:
document.getElementById('container').onclick = function clickEvent(e) {
var rect = e.target.getBoundingClientRect();
var x = e.clientX - rect.left; //x position within the element.
var y = e.clientY - rect.top; //y position within the element.
console.log("Left? : " + x + " ; Top? : " + y + ".");
}
我的尝试:https://jsfiddle.net/3g8un5w1/5/
即使通过 css 缩放,我也希望能够在画布上的圆圈位置和鼠标指针位置之间进行转换。