See attached image – How do I center align all the text
in the blue rect
? I’ve done it by eye so far, using x
, but in real life I won’t be able to do this as the text lengths will vary. The original rectangle was drawn in Inkscape.
The svg:
<g
id="g2450">
<rect
width="30"
height="40"
stroke="#00ffff"
fill-opacity="0"
id="sensor-info"
>
</rect>
<g
id="sensor-info-text"
transform="matrix(0.51584178,0,0,0.51641502,11.648419,22.062229)"
/>
</g>
I then append the following in javascript:
let s = document.getElementById ('sensor-info-text');
s.innerHTML = `
<text
x="-20" y="-20"
font-family="Verdana"
font-size="12px"
fill="#0000ff">
<tspan >${sensor.Name}</tspan>
<tspan x="-5" dy="20px" >${sensor.SetPoint + String.fromCharCode(176) + 'C'}</tspan>
<tspan x="-5" dy="20px">${sensor.Measurement + String.fromCharCode(176) + 'C'}</tspan>
</text>
`
I’ve tried svg text {dominant-baseline:middle;text-anchor:middle;}
in the css
, as suggested here: https://stackoverflow.com/questions/5546346/how-to-place-and-center-text-in-an-svg-rectangle
, but the text "flies off" to the right if I unset e.g. x
.
How do I proceed?
2
Answers
You need to calculate suitable x/y coordinates for your
<text>
elements according to your<rect>
elements position.The problem: svg
<text>
elements don’t behave like HTML block elements.So
dominant-baseline
will only shift each text baselines.It won’t take the text elements total height as a reference.
Here’s an example of a labeling helper function:
How it works
get bounding box of a
<rect>
and calculate a centroid/center point via customgetBBoxTransform(el)
helper. This function will calculate a bounding box also respecting transformations (e.g inherited from parent groups)generate
<tspan>
elements for pseudo-lines (by splitting text content according to a defined seperator like "||"count lines and calculate the
<text>
y attribute valueYou’ll need to adjust font-sizes to get the desired result.
This alternative works for the first
<rect>
from HerrStrietzel his answer because the<path>
and<text>
are injected in the<g>
where the transform is applied.Does not work for the second
<rect>
where the transform is applied on the rect itself.