Render diagrams on the fly in your Blazor apps
Nothing beats a good diagram!
If you’ve ever tried to describe your software’s architecture using just words you know the power of an effective visual.
But what if you want to define that diagram using a simple text based language, then render it in your Blazor app?
Turns out you can, using something called GraphViz and a teeny tiny bit of javascript interop.
First you’ll need to reference a few JS scripts in your index.html
file (if using Blazor WASM).
Then you’ll need to write a tiny bit of javascript code.
wwwroot\diagrams.js
The latest version of .NET 5 makes it possible to import javascript modules like this one, so over in a Blazor component you can do something like this…
Markup
Code
This imports our diagrams.js
javascript. We’re then able to call the renderDot
method, passing in the following:
- The “markup” for a diagram written using DOT language
- A reference to the
div
where we want the diagram to be rendered
That’s all there is to it. Run this now and you should see an SVG of your diagram, rendered right there in your Blazor component!
Now admittedly this graph is not all that impressive, but from here you can create all sorts of things…
Here’s a slightly more involved example.
And here’s the DOT code for it…
Happy graphing!#
For more examples check out the GraphViz web site.
If you want to play around with your own DOT diagrams you can give it a whirl in the online editor here.