【发布时间】:2021-03-25 12:03:34
【问题描述】:
我需要在 SVG 平面图上的房间中心放置标记(圆圈)。每个房间可以是单个形状(如矩形)或一组形状。圆圈应覆盖房间的大约 1/4: 半径 = (宽 + 高) / 8
经过大量的试验和错误后,我想出了一些似乎可以工作的代码,但在我使用 getBBox()、getBoundingClientRect() 和 matrixTransform() 时也显得过于复杂:
- getBBox 为我提供了正确的宽度和高度,但对于组元素,x = y = 0
- getBoundingClientRect + matrixTransform 给了我正确的 cx 和 cy 坐标,但不是正确的房间宽度和高度。
有没有更简单的方法?
const draw = document.getElementsByTagName("svg")[0];
const NS = draw.getAttribute("xmlns");
// Get titles
const titleElements = draw.getElementsByTagNameNS(NS, "title");
Array.from(titleElements).forEach((titleElement) => {
let parentElement = titleElement.parentElement;
let clientRect = parentElement.getBoundingClientRect();
let bbox = parentElement.getBBox();
let point = draw.createSVGPoint();
point.x = clientRect.left + clientRect.width / 2;
point.y = clientRect.top + clientRect.height / 2;
// Convert screen coordinates into SVG document coordinates
const svgP = point.matrixTransform(draw.getScreenCTM().inverse());
// clientRect doesn't resize with the svg
// let radius = (clientRect.width + clientRect.height) / 8;
// bbox resizes with the svg
let radius = (bbox.width + bbox.height) / 8;
let circle = document.createElementNS(NS, "circle");
circle.setAttribute("cx", svgP.x.toString());
circle.setAttribute("cy", svgP.y.toString());
circle.setAttribute("r", radius.toString());
circle.setAttribute("fill", "cyan");
draw.appendChild(circle);
});
<!DOCTYPE html>
<html>
<head>
<title>Floor Plan</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app" style="width:300px;height:300px;">
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:ev="http://www.w3.org/2001/xml-events"
viewBox="0 0 792 612"
xml:space="preserve"
color-interpolation-filters="sRGB"
class="st7"
>
<g>
<g id="group1-1" transform="translate(659.691,-186.346) rotate(60)">
<title>Space.1001</title>
<g id="shape1-2">
<rect x="0" y="508.5" width="90" height="90" class="st1" />
</g>
</g>
<g id="group1000-10" transform="translate(482.508,-114.75) rotate(60)">
<title>Space.1000</title>
<g id="shape1000-11">
<rect x="0" y="208.5" width="90" height="90" class="st4" />
</g>
</g>
<g id="group1002-18" transform="translate(659.691,-67.0962) rotate(60)">
<title>Space.1002</title>
<g id="shape1002-19">
<rect x="0" y="508.5" width="90" height="90" class="st5" />
</g>
</g>
<rect x="0" y="208.5" width="90" height="90" class="st6">
<title>Space.1004</title>
</rect>
</g>
</svg>
</div>
</body>
</html>
【问题讨论】:
-
你的代码基本正确。使用
getBoundingClientRect()并使用getScreenCTM().inverse()进行转换,或者使用getBBox()并使用getCTM().inverse()进行转换。 -
问题是我使用的是getBoundingClientRect“和”getBBox,而不是“或”。这就是为什么我怀疑必须有更好的方法。但如果我只尝试其中一个,它就会失败。
-
您的代码分配了
bbox,但从不使用它。 -
我已经修复了代码并重新表述了我的问题。谢谢@ccprog!
-
啊。我看到了我的错误。
.getCTM()将变换赋予初始视口,而不是初始坐标系。那么最好的方法就是按照保罗的回答,在转换后的组内移动圆圈。
标签: javascript svg