我有一个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>
我需要知道每个圆相对于 parent 的相对坐标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 缩放的。
也许只是添加id
到它circle
本身,然后读取它的cx
和cy
属性?如果 divpadding
设置为0
,则它应该是相对的x
和y
。如果填充不同,则需要将此填充添加到x
和y
。
请注意,它是圆心的 x,y。检查下面的示例。起初它读取x
,y
圆的,然后(2秒后)将其设置为0
,0
。您可以看到,它是相对于div
边界 ( red
) 的。
例如10px
,如果 div 填充是,该值仍然是 100、100,但相对于容器,您必须添加它10
,因此它应该返回100 + padding
, 100 + padding
( 110
, 110
)。而二传手应该是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>
评论后编辑
检查带有比例示例的小提琴(根据您的评论小提琴):https : //jsfiddle.net/r7ckLfhv/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句