This tutorial shows how to load graph data from a Json string and create diagram objects corresponding to the graph nodes and edges. The code is also available in Samples folder of JsDiagram distribution.
1. Create a text file called Tutorial1.txt and add the following Json string to it:
XML Copy Code |
---|
{"nodes":[ |
2. Create empty Tutorial1.html and Tutorial1.js files, and add DIV and CANVAS elements to the HTML page.
HTML Copy Code |
---|
<!-- The DiagramView component is bound to the canvas element below --> |
3. Add script references to the MindFusion UMD scripts and Tutorial1 JavaScript files:
HTML Copy Code |
---|
<script src="umd/collections.js" type="text/javascript"></script> |
4. In Tutorial1.js, assign shorter names to the DiagramView, Diagram, ShapeNode, DiagramLink, LayeredLayout and Rect classes (if using diagram's ES6 or CommonJS modules, these would be import or require statements for respective classes and modules).
JavaScript Copy Code |
---|
var DiagramView = MindFusion.Diagramming.DiagramView; var Rect = MindFusion.Drawing.Rect; |
5. Add a DOMContentLoaded handler that creates a DiagramView instance wrapping the HTML Canvas element:
JavaScript Copy Code |
---|
var diagram; document.addEventListener("DOMContentLoaded", function () |
6. Add the following code to the DOMContentLoaded handler to create a network request that loads the Json file from the server:
JavaScript Copy Code |
---|
// pretend we are calling a web service |
7. Implement the onreadystatechange handler to parse the json file:
JavaScript Copy Code |
---|
if (this.readyState == 4 && this.status == 200) |
8. Add the buildDiagram function that creates diagram nodes and links for each object from the parsed Json graph:
JavaScript Copy Code |
---|
function buildDiagram(graph) |
9. Finally, apply LayeredLayout to arrange the diagram automatically:
JavaScript Copy Code |
---|
// arrange the graph |
10. Publish MindFusion.*.js and tutorial files using web server of your choice. Now you should see this if you open Tutorial1.html in a web browser: