Last year, I started to use Excalidraw as a diagram tool. However, the SVG images didn’t display the font correctly. In this post, I’d like to explain the problem and offer a solution.
Let’s create a sample drawing with Excalidraw. If you open the link, it should look something like this:
However, in a browser, it looks like this:
Note that the site doesn’t allow uploading SVGs for security reasons. Hence, images in this post are only for illustration purposes. If you want to check the SVGs, please check the original post
The code is straightforward:
src="https://dev.to/path/to/sample.svg">
The font doesn’t display correctly. The problem is that the SVG references fonts hosted on the Excalidraw site, but the browser blocks loading external resources within the
tag.
- Load a font
Here are a couple of possible solutions.
Inline the SVG
An alternative is to copy-paste the content of the SVG file inside the HTML page.
The result conforms to our expectations:
The downside is that you need to copy-paste the new code when changes happen.
Embed the font as data
Another alternative is to transform the font to raw Base 64 data. I found this online tool very handy. We can update the SVG with the data:
Because the SVG is self-contained, it now works:
The downside is that we cannot use the image directly; we need the additional transform processing step.
Use the tag
The last option is the most straightforward one and the one I chose: instead of the
tag, use the tag. For some reason, probably profoundly buried in a specification, the browser allows loading external resources from objects. This is the replacement code:
Note the same original SVG, without any changes. And here’s the result:
The downside is that you don’t get any features from the
tag.
Conclusion
In this post, I’ve explained one of the issues of using embedded SVGs in HTML and a couple of alternatives to work around it.
To go further:
Originally published at A Java Geek on January 21th, 2024