我有一个 12 小时时钟,有 47 个刻钟区域(12 小时 * 一小时 4 个刻钟)。我想根据后端的响应在时钟的定义的四分之一区域上显示一个点。假设后端返回我3
,我必须在第三季度区域显示一个点。
这是一个 fiddle :jsfiddle
这是我的方法:
SVG 中的所有四分之一区域都在 <g id="data"></g>
组中。每个区域都有一个 id。之后我想确定他的 SVG 位置,然后在该位置上放置一个点:
function setPointForQuarterCoordonates(id) {
var quarterObject = document.getElementById(id);
var coordinates = quarterObject.getBoundingClientRect();
var point = document.createElementNS(NS, 'circle');
point.setAttributeNS(null, 'cx', coordinates.x);
point.setAttributeNS(null, 'cy', coordinates.y);
point.setAttributeNS(null, 'r', 10);
return point;
}
在我的示例中,“显示定义点 (3)”按钮通过在从 12:00 开始的第三个矩形上添加一个点来模拟此事件。为此,我使用了:
var quarterCoordinates = quarterObject.getBoundingClientRect();
但问题是,这给了我 DOM 坐标,而不是 SVG 坐标。因此,如果我调整窗口大小并第二次单击该按钮,该点将添加到不同的位置,而不是相同的位置。
您对如何处理这个问题有什么想法或建议吗?
最佳答案
尝试使用 .getBBox();
而不是 getBoundingClientRect();
。
function setPointForQuarterCoordonates(id) {
var quarterObject = document.getElementById(id);
var coordinates = quarterObject.getBBox(); // <------------------
var point = document.createElementNS(NS, 'circle');
point.setAttributeNS(null, 'cx', coordinates.x);
point.setAttributeNS(null, 'cy', coordinates.y);
point.setAttributeNS(null, 'r', 10);
return point;
}
https://developer.mozilla.org/en-US/docs/Web/API/SVGGraphicsElement/getBBox
关于javascript - 在 SVG 上的所需位置上显示一个点(圆),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60741891/