How to draw context diagram in SVG base on the returned json data?
Sample json data:
"data":{
"PageType":"Home",
"CatId":0,
"Category":"",
"ObjectId":0,
"Object":"",
"Total":1,
"Prev":[
{
"type":"Prev1",
"Count":1,
"Time":0
},
{
"type":"Prev2",
"Count":2,
"Time":0
},
{
"type":"Prev3",
"Count":3,
"Time":0
},
],
"Next":[
{
"type":"Next1",
"Count":1,
"Time":1000
}
{
"type":"Next2",
"Count":2,
"Time":1000
},
{
"type":"Next3",
"Count":3,
"Time":1000
}
]
}
OK, this is not a problem, it is just implementation exercise. I'm not giving you the result, but just some pointers. These are the basic elements of your SVG. The <g> is grouping the elements and can be moved around with the transform attribute.
<svg viewBox="0 0 400 300" xmlns="http://www.w3.org/2000/svg">
<style>
line, rect {stroke-width: 1; stroke: navy; fill: none;}
text {fill: navy;}
</style>
<g transform="translate(200 150)">
<rect x="-50" y="-20" width="100" height="40" rx="10" />
<text dominant-baseline="middle" text-anchor="middle" width="100">Text 1</text>
<line x1="50" y1="0" x2="100" y2="60" />
</g>
</svg>
Then it needs to be dynamic. You know the size of each element and the spacing. With a forEach() loop you can loop through all the elements in a list and "spread" them out. I just "append" the new SVG elements with ...innerHTML += ...
var prev = {
"Prev": [{
"type": "Prev1",
"Count": 1,
"Time": 0
},
{
"type": "Prev2",
"Count": 2,
"Time": 0
},
{
"type": "Prev3",
"Count": 3,
"Time": 0
},
]
};
var drawing = document.getElementById('drawing');
prev.Prev.forEach((p, i, arr) => {
let x = 55;
let y = 250/arr.length*i+50;
drawing.innerHTML += `<g transform="translate(${x} ${y})">
<rect x="-50" y="-20" width="100" height="40" rx="10" />
<text dominant-baseline="middle" text-anchor="middle" width="100">${p.type}</text>
<line x1="50" y1="0" x2="100" y2="${250/arr.length-y+50}" />
</g>`;
});
<svg id="drawing" viewBox="0 0 400 300" xmlns="http://www.w3.org/2000/svg">
<style>
line, rect {stroke-width: 1; stroke: navy; fill: none;}
text {fill: navy;}
</style>
</svg>
This should be fine for implementing the entire thing yourself :-)