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: ${amount}ℓ
"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 volume
.
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 end
.
Each node is visualized as a row and has the following properties:
min
, max
- The earliest and latest allowed timestart
, end
- The earliest and latest possible timeUsing 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
using 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