Search code examples
reactjsreact-konvakonva

How to add text inside rectangle in React Konva?


I am using React Konva to draw shapes. I want to insert a question mark inside the last rectangle. The code I'm using is as below. But it doesn't quite work:

<Grid item xs={12} lg={3} style={{border:'5px 5px 5px 5px solid white'}}>
    <Stage width={1200} height={1200}>

      <Layer>
      
        <RegularPolygon
          sides={3}
          x={50}
          y={100}
          width={100}
          height={100}
          stroke="orange"
        />

<RegularPolygon
          sides={3}
          x={200}
          y={100}
          width={100}
          height={100}
        //   fill="red"
          stroke="#00FFFF"
        />

<Rect
        
          x={300}
          y={50}
          width={80}
          height={80}
       
          stroke="orange"
        //   shadowBlur={5}
        />
  <Group x={450} y={30}>
<Rect
          x={430}
          y={40}
          width={100}
          height={100}
        
          stroke="white"
          strokeWidth={5}
          
        >
          <Text
                  fontSize={20}
                  text="?"
                  stroke='white'
                  strokeWidth={5}
                  align="center"
                />
        </Rect>
        </Group>
      </Layer>
    </Stage>
    </Grid>

I've added the Group tag with Text to make it work but it doesn't work.


Solution

  • Have you tried not wrapping Text with Rect and adding x & y props to Text?

    <Rect
      x={430}
      y={40}
      width={100}
      height={100}
      stroke="white"
      strokeWidth={5}
    />
    <Text
      fontSize={20}
      text="?"
      stroke='white'
      strokeWidth={5}
      align="center"
      // similar coordinates than your Rect component
      x={480}
      y={90}
    />
    

    Check this codesandbox example