csssvgtextlayoutreact-native-svg

In SVG, how to center Text along a path?


Objective: Create a curved Path from A to B. Center the text on the path.

It doesn't seem like this is possible. enter image description here

In my example below, startOffset=50% will begin the text at the 50% mark. However, I'd like to get the center of the text to be at this mark rather than the start of the text.

If anyone could help me out I'd appreciate it. Thank you.

import React from 'react'
import { Dimensions, View, StyleSheet } from 'react-native'
import Svg, { Defs, Path, Mask, G, Rect, Use, Circle, Text, TextPath } from 'react-native-svg'

const CenterTextExample = (props) => {
    const radius = 150
    const centerX = 350
    const centerY = 350

    // This path defines a half-circle
    const path = `M${centerX - radius},${centerY} A${radius},${radius} 0 0,1 ${centerX + radius},${centerY}`

    return (
        <View style={styles.container}>
            <Svg height="700" width="700">
                <Path id="halfCirclePath" d={path} fill="none" stroke="blue" />
                <Text fill="black" fontSize="32">
                    <TextPath href="#halfCirclePath" startOffset="50%" textAnchor="middle">
                        centerThisText
                    </TextPath>
                </Text>
            </Svg>
        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
})

export default CenterTextExample

Solution

  • The text-anchor attribute should be on the text element, not the textPath element.

    <svg width="700" height="700">
      <path id="halfCirclePath" d="M200 350 A 150 150 0 0 1 500 350" fill="none" stroke="blue" />
      <text fill="black" font-size="32" text-anchor="middle">
        <textPath href="#halfCirclePath" startOffset="50%">centerThisText</textPath>
      </text>
    </svg>