简体   繁体   English

React-Konva 文本居中/从中心生长

[英]React-Konva Text Centering / Growing From Center

I am trying to draw a triangle on screen, and pin labels to each vertex of the triangle.我正在尝试在屏幕上绘制一个三角形,并将标签固定到三角形的每个顶点。 To accomplish this, I have opted to use React-Konva.为此,我选择使用 React-Konva。 I create the triangle by drawing lines towards points which I have listed manually (As a percentage of window.inner..), and I am planning on adding the labels by subtracting or adding a certain margin to these calculated vertex locations.我通过向我手动列出的点(作为 window.inner 的百分比)绘制线条来创建三角形,并且我计划通过在这些计算的顶点位置上减去或添加一定的边距来添加标签。

            <Stage width={maxwidth} height={maxheight} style={{marginLeft:'50px'}}>
                <Layer>
                    <Text 
                        text={survData[index + 1].question.options[0]} 
                        x={shapewidth/2} 
                        y={margin/2} 
                        fontSize={20} 
                        align="center"
                    />
                    <Shape
                        sceneFunc={(context, shape) => {
                            context.beginPath();
                            context.moveTo(shapewidth / 2, margin);
                            context.lineTo(margin, (shapeheight - margin));
                            context.lineTo(shapewidth - margin, (shapeheight - margin));
                            context.closePath();
                            context.fillStrokeShape(shape);

                        }}
                        fill="#00D2FF"
                        stroke="black"
                        strokeWidth={4}
                    />
                </Layer>
            </Stage>

The length of the labels that sit on the vertices of the triangle are variable, so it would be nice if they remain centered.位于三角形顶点上的标签的长度是可变的,所以如果它们保持居中会很好。 The docs suggest that I can center the text using a HTML-like 'align' property.文档建议我可以使用类似 HTML 的“对齐”属性使文本居中。 As you can see, I have attempted to implement this, but regardless, I get the following.如您所见,我试图实现这一点,但无论如何,我得到以下信息。 图片 The text is not correctly centered around the vertex.文本未正确围绕顶点居中。 Can anyone point out the mistake I'm making, or if there is a better way?谁能指出我正在犯的错误,或者是否有更好的方法?

align: center works relative to defined width of a text shape. align: center相对于文本形状的定义width起作用。 You can put your text at the start of the shape ( x = 0 ), set text width equal to shape width.您可以将文本放在形状的开头( x = 0 ),将文本宽度设置为等于形状宽度。

<Text
  text="Sample text"
  x={0}
  y={margin / 2}
  width={shapewidth}
  fontSize={20}
  align="center"
/>

Demo: https://codesandbox.io/s/stoic-mcnulty-ohxs11?file=/src/index.js演示: https ://codesandbox.io/s/stoic-mcnulty-ohxs11?file=/src/index.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM