javascript - 如何重新计算相对坐标?

标签 javascript svg

我有一个 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 缩放的。

最佳答案

也许只需添加 idcircle本身,然后读取它的 cxcy属性?如果divpadding设置为0 ,应该是亲戚xy 。如果填充不同,则需要将此填充添加到 xy .

请注意,它是圆心的 x,y。检查下面的示例。首先它读取 x , y的圆,然后(2 秒后)将其设置为 0 , 0 。您可以看到,它是相对于div边框(red)。

如果 div 填充例如为 10px ,该值仍然是 100, 100,但相对于容器,您必须添加 10 ,所以它应该返回 100 + padding , 100 + padding ( 110110 )。 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/

相关文章:

javascript - 如何使用 d3.js 将外部组添加到现有 svg?

java - 如何在 Android 应用程序中运行用户提供的任意代码?

javascript - 在 jQuery 中如何删除变量和函数

javascript - Node.JS:从 JSON 对象请求键值对

javascript - 使用vue和node js将JSON文件上传到我的服务器

google-maps - 使用 svg 标记时缩放期间的 Google map 标记对齐问题

javascript - 如何修复滚动内容时由 SVG 触发的 Bootstrap 工具提示的不正确偏移?

javascript - 为什么ajax一个接一个发送请求

html - 我可以根据浏览器类型使用不同的 CSS 背景图片吗?

javascript - SVG - 如何将笔划从虚线变为实线?