通过getBoundingClientRect()获取正确的视口坐标

Getting the Correct Viewport Coordinates via getBoundingClientRect()

本文关键字:视口 坐标 获取 getBoundingClientRect 通过      更新时间:2023-09-26

对交互式信息图进行最后的润色,我将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的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 + ")");