【发布时间】:2020-02-17 07:11:45
【问题描述】:
我正在使用React Diagrams 创建一个应用程序。为了创建自定义节点,我使用 SVG。一个基本的自定义节点反应组件如下所示,它将呈现在画布般的区域中。
const S = {
Container: styled.div<{ height: string; width: string }>`
width: ${props => props.width};
height: ${props => props.height};
`
};
export default (props) => {
return (
<S.Container
width="100px"
height="100px"
>
<svg width="100%" height="100%" fontSize="20px">
<rect x="0" y="0" width="100%" height="100%" fill="white" />
<text x="50%" y="50%" textAnchor="middle" ref={text}>
Hello World
</text>
</svg>
</S.Container>
);
};
所以,我有多个类似的节点,但我无法在这些节点之间保持相同的字体大小。
举个例子,
#container1 {
position: relative;
width: 100px;
height: 100px;
}
#container2 {
width: 100px;
height: 100px;
}
<!--------------- DIAMOND NODE --------------->
<div id="container1">
<svg
preserveAspectRatio="none"
width="100%"
height="100%"
viewBox="0 0 200 200">
<polygon
fill="mediumpurple"
stroke="black"
strokeWidth="4px"
strokeMiterlimit="10"
points="0,100 100,0 200,100 100,200" />
<text
x="50%"
y="50%"
dominant-baseline="middle"
text-anchor="middle">
Hello World
</text>
</svg>
</div>
<!--------------- RECT NODE --------------->
<div id="container2">
<svg
width="100%"
height="100%">
<rect
x="0"
y="0"
width="100%"
height="100%"
fill="white"
stroke="black"
strokeWidth="4px" />
<text
x="50%"
y="50%"
dominant-baseline="middle"
text-anchor="middle">
Hello World
</text>
</svg>
</div>
在Diamond 节点中,定义viewBox 很重要,因为据我所知,无法使用百分比来定义点。如果我更改viewBox="0 0 1000 1000" 和points="0,500 500,0 1000,500 500,1000",文本会更小。如何使那些 svg 文本元素以相同大小显示文本
请注意,我将svgs 的大小保持为100%,因为我想调整组件的宽度以匹配文本的长度,在这种情况下,我所要做的就是调整容器的大小@ 987654332@ 和 svg 将填补空白。
【问题讨论】:
-
为什么不在两者中都使用 viewBox?