I'm implementing a network chart using Vis.js, and I'd like to have a grid as background Do you have any idea how can I achieve that and if I can achieve that?
Can I have a grid as background on a Vis.js Network
755 views Asked by Donovant At
2
There are 2 answers
0
On
Example using beforeDrawing (per this example):
// create an array with nodes
var nodes = new vis.DataSet([
{ id: 1, value: 2, label: "Algie" },
{ id: 2, value: 31, label: "Alston" },
{ id: 3, value: 12, label: "Barney" },
{ id: 4, value: 16, label: "Coley" },
{ id: 5, value: 17, label: "Grant" },
{ id: 6, value: 15, label: "Langdon" },
{ id: 7, value: 6, label: "Lee" },
{ id: 8, value: 5, label: "Merlin" },
{ id: 9, value: 30, label: "Mick" },
{ id: 10, value: 18, label: "Tod" },
]);
// create an array with edges
var edges = new vis.DataSet([
{ from: 2, to: 8, value: 3, title: "3 emails per week" },
{ from: 2, to: 9, value: 5, title: "5 emails per week" },
{ from: 2, to: 10, value: 1, title: "1 emails per week" },
{ from: 4, to: 6, value: 8, title: "8 emails per week" },
{ from: 5, to: 7, value: 2, title: "2 emails per week" },
{ from: 4, to: 5, value: 1, title: "1 emails per week" },
{ from: 9, to: 10, value: 2, title: "2 emails per week" },
{ from: 2, to: 3, value: 6, title: "6 emails per week" },
{ from: 3, to: 9, value: 4, title: "4 emails per week" },
{ from: 5, to: 3, value: 1, title: "1 emails per week" },
{ from: 2, to: 7, value: 4, title: "4 emails per week" },
]);
// create a network
var container = document.getElementById("mynetwork");
var data = {
nodes: nodes,
edges: edges,
};
var options = {
nodes: {
shape: "dot",
},
};
var network = new vis.Network(container, data, options);
network.on("beforeDrawing", function(ctx) {
var width = ctx.canvas.clientWidth;
var height = ctx.canvas.clientHeight;
var spacing = 40;
var gridExtentFactor = 4;
ctx.strokeStyle = "lightgrey";
// draw grid
ctx.beginPath();
for (var x = -width * gridExtentFactor; x <= width * gridExtentFactor; x += spacing) {
ctx.moveTo(x, height * gridExtentFactor);
ctx.lineTo(x, -height * gridExtentFactor);
}
for (var y = -height * gridExtentFactor; y <= height * gridExtentFactor; y += spacing) {
ctx.moveTo(width * gridExtentFactor, y);
ctx.lineTo(-width * gridExtentFactor, y);
}
ctx.stroke();
});
#mynetwork {
width: 600px;
height: 200px;
border: 1px solid lightgray;
background-color: none;
}
<script type="text/javascript" src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>
<div id="mynetwork"></div>
vis-network uses a html5 canvas to draw the chart. You could draw the grid yourself using the
beforeDrawingevent. To support interactivity like zooming and panning you would also need to listen to thedragStart,dragginganddragEndevents as well aszoom. With these events it should be possible to implement a fully interactive background.Have a look at the renderEvents example and the interactionEvents example.