是否可以在 SVG 中定义某种锚点/参考点?理想情况下作为一个属性,可能是自定义的,因为我还没有找到一些内置的。 这种属性的可能应用与文本锚点非常相似: 文本锚
我的主要目的是能够将一个 SVG 放置在另一个之上,就像将文本放置在 SVG 的特定点上一样。这个想法是为了简单起见,每个 SVG 的anchors应该在全局协调系统中match)。
感谢您提供任何信息!
类似问题:transform-translate
下面是我最近创建的一个函数,在这种情况下可能会有用。它在矩形周围创建 8 个均匀分布的锚点,并在单击时显示它们。锚点坐标是手动设置的,但可以通过公式轻松添加。
<!DOCTYPE html>
<html>
<head>
<title>SVG Rectangle with Anchor Points</title>
</head>
<body>
<svg id="svg" width="400" height="400" viewBox="0 0 400 400"></svg>
<script>
// create the SVG element
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", "400");
svg.setAttribute("height", "400");
document.body.appendChild(svg);
// create the rectangle
var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
rect.setAttribute("x", "50");
rect.setAttribute("y", "50");
rect.setAttribute("width", "300");
rect.setAttribute("height", "300");
rect.setAttribute("fill", "transparent");
rect.setAttribute("stroke", "black");
svg.appendChild(rect);
// create the anchor points
var anchorRadius = 5;
var anchorCoords = [
{x: 50, y: 50}, // top-left corner
{x: 200, y: 50}, // top edge midpoint
{x: 350, y: 50}, // top-right corner
{x: 350, y: 200}, // right edge midpoint
{x: 350, y: 350}, // bottom-right corner
{x: 200, y: 350}, // bottom edge midpoint
{x: 50, y: 350}, // bottom-left corner
{x: 50, y: 200}, // left edge midpoint
];
for (var i = 0; i < anchorCoords.length; i++) {
var anchor = document.createElementNS("http://www.w3.org/2000/svg", "circle");
anchor.setAttribute("cx", anchorCoords[i].x);
anchor.setAttribute("cy", anchorCoords[i].y);
anchor.setAttribute("r", anchorRadius);
anchor.setAttribute("fill", "blue");
anchor.setAttribute("opacity", "0");
svg.appendChild(anchor);
}
// add click event to the SVG element to show/hide the anchor points
svg.addEventListener("click", function(event) {
if (event.target === rect) {
var anchors = svg.getElementsByTagName("circle");
for (var i = 0; i < anchors.length; i++) {
if (anchors[i].getAttribute("opacity") == "0") {
anchors[i].setAttribute("opacity", "1");
} else {
anchors[i].setAttribute("opacity", "0");
}
}
}
});
</script>
</body>
</html>