【发布时间】:2018-09-09 06:17:47
【问题描述】:
我正在尝试使用遵循 svg 多边形轮廓的 svg 路径创建形状。
我需要设置 svg path 元素的 d 属性,因为形状的大小会根据添加到文档中的 <text /> 元素中的文本量而有所不同。我将有许多这样的形状,但为了简洁起见,我只是在这里展示一个。
我的逻辑是尝试基本上从中间开始,向下向右移动 60 度,回到中间向左向下移动 60 度,然后将框的左侧连接起来。
我的体型不太对劲。有很多问题:
形状与六边形的点不一致。
出现对角线的每条平线或
H的长度不同。有一条流氓线试图连接回形状的点。
我需要在拐角处添加曲线,但我不知道该怎么做。
const getPoint = ({
sides,
size,
center,
rotate,
side
}) => {
const degrees = (360 / sides) * side - rotate;
const radians = (Math.PI / 180) * degrees;
return {
x: center.x + size * Math.cos(radians),
y: center.y + size * Math.sin(radians)
};
};
const path = document.querySelector('path');
const gRef = document.querySelector('.hierarchy-label__container');
gRef.setAttribute('transform', 'translate(0, -40)');
const gbBox = gRef.getBBox();
let startingX = gbBox.x + gbBox.width / 2;
const startingY = gbBox.y + gbBox.height;
startingX = startingX - 0.7;
const [bottomRight, bottomLeft] = [1, 4].map((side) =>
getPoint({
sides: 6,
size: 30,
center: { x: startingX, y: startingY },
side,
rotate: 30
})
);
const bottomRightCoords = `${bottomRight.x} ${bottomRight.y}`;
path.setAttribute(
'd',
`M ${startingX} ${startingY} L ${bottomRightCoords} H ${gbBox.width} M ${startingX} ${startingY} L ${
bottomLeft.x
} ${bottomRight.y} H -${gbBox.width + 4} V -${gbBox.height} H ${gbBox.width} L ${gbBox.width} ${
bottomRight.y
} M ${startingX} ${startingY} Z`
);
.hierarchy-label__text {
fill: white;
text-anchor: middle;
font-size: 1.2rem;
}
<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 990 759">
<g class="vx-group vx-cluster" transform="translate(100, 100)">
<g class="vx-group" transform="translate(0, 0)">
<g class="vx-group node-vertical__container" transform="translate(490, 0)">
<polygon points="25.98076211353316,-14.999999999999998 25.98076211353316,14.999999999999998 1.83697019872103e-15,30 -25.98076211353316,14.999999999999998 -25.980762113533157,-15.000000000000004 -5.510910596163089e-15,-30"></polygon>
<g class="vx-group node-vertical__business-unit" transform="translate(0, 0)">
<use xlink:href="#icon-BusinessUnit"></use>
</g>
<g class="hierarchy-label__container" transform="translate(0,-40)">
<text class="hierarchy-label__text" width="50" fill="white" x="0" y="0" text-anchor="middle" style="pointer-events: none;">
<tspan x="0" dy="0em">Finance</tspan>
</text>
<path></path>
</g>
</g>
</g>
</g>
</svg>
【问题讨论】: