Building an HTML5 mermaid.js visualization application
Creating a visualization app for mermaid.js is a practical solution for testing and refining diagrams before integrating them into web pages. I designed this app using Bootstrap for responsive layout, custom CSS for styling, and JavaScript to enable real-time rendering of diagrams.
The app allows users to input mermaid.js code into a textarea and instantly preview the rendered diagram. The interface is straightforward, with a split layout where the input is on the left, and the preview area is on the right. This design ensures clarity and usability.
HTML Structure
The HTML uses Bootstrap for responsive grid-based design. Below is a snippet of the code:
<div class="row">
<div class="col-md-6">
<textarea id="code" class="form-control" rows="10" placeholder="Enter mermaid code here..."></textarea>
</div>
<div class="col-md-6">
<div id="preview" class="border p-3">Your diagram will appear here...</div>
</div>
</div>
Styling the Layout
I used custom CSS to enhance the visual presentation. For example, the textarea and preview area are styled for consistency and ease of use:
#code {
background-color: #2C2C2C;
color: #F8F8F2;
font-family: monospace;
min-height: 300px;
}
#preview {
background-color: #f9f9f9;
overflow: auto;
border-left: 1px solid #ddd;
min-height: 300px;
}
Real-Time Rendering with JavaScript
The core functionality is achieved with a small JavaScript script that listens for input events on the textarea and updates the preview dynamically:
$('#code').on('input', function () {
const preview = ('#preview');
const code = $(this).val();
try {
preview.html(`<div class="mermaid">{code}</div>`);
mermaid.init(undefined, $preview.find('.mermaid')[0]);
} catch (err) {
$preview.html('<p class="text-danger">Invalid Mermaid syntax</p>');
}
});
This script ensures users see their diagrams rendered instantly, helping them verify and adjust their code effectively.
Conclusion
This visualization app is a useful tool for anyone working with mermaid.js diagrams, particularly in academic or engineering contexts where precision matters. By combining Bootstrap for layout, custom CSS for style, and JavaScript for functionality, I created an efficient and user-friendly solution.
For more insights into this topic, you can find the details here.