我有一个 div block :
<div id="container"></div>
此 block 内有一个带有 SVG 圆圈的 SVG 路径。当我点击时,我得到相对坐标 id="container"
。左上角为 0,0。
SVG 元素始终是容器的全宽、全高。但 SVG 有自己的视口(viewport)。
如何重新计算 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/
我希望能够在 Canvas 上圆圈的位置和鼠标指针位置之间进行转换,即使它是通过 css 缩放的。
最佳答案
也许只需添加 id
到circle
本身,然后读取它的 cx
和cy
属性?如果divpadding
设置为0
,应该是亲戚x
和y
。如果填充不同,则需要将此填充添加到 x
和y
.
请注意,它是圆心的 x,y。检查下面的示例。首先它读取 x
, y
的圆,然后(2 秒后)将其设置为 0
, 0
。您可以看到,它是相对于div
边框(red
)。
如果 div 填充例如为 10px
,该值仍然是 100, 100,但相对于容器,您必须添加 10
,所以它应该返回 100 + padding
, 100 + padding
( 110
, 110
)。 setter 应该是 110 - padding
, 110 - padding
.
<div id="container" style="padding:0px; border:1px solid red;">
<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" id="circle"></circle>
</svg>
</div>
<script>
console.log('Before:');
console.log(document.getElementById('circle').getAttribute('cx') + ', '+ document.getElementById('circle').getAttribute('cy'));
setTimeout(function(){
console.log('After setting to 0,0.'); document.getElementById('circle').setAttribute('cx',0)
document.getElementById('circle').setAttribute('cy',0)},2000);
</script>
评论后编辑
检查 fiddle 的比例示例(基于您的评论 fiddle ): https://jsfiddle.net/r7ckLfhv/
关于javascript - 如何重新计算相对坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68572714/