I'm trying to display text in Leaflet using a marker layer with icon as L.divIcon (with svg text). This works fine. However when the text is rotated the text is clipped outside the viewport. I've tried to adjust this in several ways, but to no avail. For example, I've tried to extract the BBox after rotation, and then update the svg viewBox parameters, but this doesn't work as expected.
Here you can see the viewbox of the svg containing rotated text. The text content 125BET is clipped. The text 10665 is barely rotated, and is displayed correctly.
Here is the viewbox of the text component, and I want to use this information to avoid clipping:
Code:
let svgIcon = L.divIcon({
html: `
<svg
version="1.1"
id="${svgGcTextId}"
preserveAspectRatio="none"
xmlns="http://www.w3.org/2000/svg"
>
<text width="5000" height="5000" x="0" y="${fontSize}" transform="rotate(${rotation})" font-size="${fontSize}">${text}</text>
</svg>`,
className: "",
iconSize: [24, 10],
iconAnchor: [0, fontSize],
});
let marker = L.marker(latlng, { icon: svgIcon, interactive: false });
Edit:
Tried adding transform-origin as per Peters suggestion. Although this seems to work, it shifts the insertion point of the text which isn't desirable. See pic below, where the "1" in 125BET is translated south of the building. It's possible to see more of the text though, as more of it is inside the viewbox.
Edit2:
Here is a fiddle. Change the rotation and fontSize values to test different scenarios. Note that I have code for scaling the font size when zooming (but that shouldn't be relevant here)
https://jsfiddle.net/6vw5z20k/20/
Edit3 - solved
Thanks to Peters input I managed to solve it with the following code. It was necessary to specify a large viewbox (e.g. 600 x 600), then insert the text in the center using x and y. It was also necessary to specify the transform-origin, so the rotation was performed correctly. Last but not least the svg had to be centered at the reference latlng using iconAnchor.
const svgIcon = L.divIcon({
html: `
<svg
version="1.1"
id="${svgGcTextId}"
preserveAspectRatio="none"
xmlns="http://www.w3.org/2000/svg"
width="600"
height="600"
>
<text x="300" y="300" transform-origin="300 300" transform="rotate(${rotation})" font-size="${fontSize}">${text}</text>
</svg>`,
className: "",
iconSize: [24, 10],
iconAnchor: [300, 300],
});
let marker = L.marker(latlng, { icon: svgIcon, interactive: false });
Lots of room to rotate the text 125BET here, but the viewbox might get to small if one zooms far in and the text is scaled too much.



