【问题标题】:Getting the Correct Viewport Coordinates via getBoundingClientRect()通过 getBoundingClientRect() 获取正确的视口坐标
【发布时间】:2013-11-21 10:40:58
【问题描述】:

对交互式信息图进行最后润色后,我将 HTML 页面上 SVG 对象的对齐方式从左侧更改为居中。这一变化打破了出现在每个州上的小弹出窗口的位置。这是左对齐的版本,可以正常工作:

http://www.50laboratories.com/demographicclout/demographicclout-left.html

以及居中的版本,错误地放置了弹出窗口:

http://www.50laboratories.com/demographicclout/demographicclout-centered.html

这是使用 getBoundingClientRect() 确定弹出位置的代码:

targetbackground = document.getElementById(selectedstate + mapyear);
targetwidth=targetbackground.getBoundingClientRect().width;
targetex = targetbackground.getBoundingClientRect().left + (targetwidth/2)+excorrection;
targetwye = targetbackground.getBoundingClientRect().top + wyecorrection;
d3.select("#datapopup").attr("transform", "translate(" + targetex + "," + targetwye + ")");

显然 getBoundingClientRect() 正在返回与浏览器窗口左上角的距离,而不是 SVG 视口的左上角。如何始终如一地获得正确的坐标值,即从视口的原点?

【问题讨论】:

  • 实际上,居中 SVG 中的弹出位置位于正确位置的右侧,而不是您所期望的左侧,如果只是从左侧边缘测量像素的简单问题浏览器窗口而不是视口,所以我真的不确定发生了什么。

标签: javascript svg d3.js coordinates


【解决方案1】:

使用 SVG 的 getBBox() 方法:

targetbackground = document.getElementById(selectedstate + mapyear);
targetwidth = targetbackground.getBBox().width;
targetex = targetbackground.getBBox().x + (targetwidth/2) + excorrection;
targetwye = targetbackground.getBBox().y + wyecorrection;
d3.select("#datapopup").attr("transform", "translate(" + targetex + "," + targetwye + ")");

【讨论】:

  • 完美。谢谢,双像素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多