Embedded SVGs on websites are a powerful design feature of modern web development. With SVGs you can create sophisticated high-quality interactive data visualizations.
But sometimes, all you want to do is put some user-provided text on a rectangle. As an example, here is a cuboid of dirt with a volume in liters.
I’ll show you three methods how to do that without specialized libraries.
`...`and replace the text you want to change dynamically. In the following example to:
"data:image/svg+xml;base64," + btoa(source)and use it as image URL.
This method is useful for creating dynamic markers in Leaflet maps:
Instead of rendering a template string to a data URI, you can add the SVG directly in your website and
manipulate it using the DOM. In this example, I’ve given the
tspan-Element the ID
React with Typescript has full support for SVG elements. The following demo project renders a timeline visualization of a sequence of nodes. The diagram consists of labels, minor guides, major guides and a line for each node.
The blue line connects all
start, the red line connects all
Each node is visualized as a row and has the following properties:
max- The earliest and latest allowed time
end- The earliest and latest possible time
Using React function components, it’s very easy to organize the different geometry producing logic. And if you use Typescript, your SVG-code is statically type checked. 👍👍
For example the label is created like this:
and the minor guide like this:
At first, I wanted to use some arbitrary coordinate system and then stretch the SVG to fit in a website
preserveAspectRatio="none" (See SVG Pocket Guide).
But then I realized that all the text is stretched too. To avoid this, each component needs to calculate the fitted x-coordinates
manually. To do that, I’m giving a small function
tx(value: number): number as a prop to all components