12

I am working on angular vis.js. Vis.js works on canvas for creating nodes and links between the nodes.

Is there any way to get the image (jpeg/png) from the visj.s canvas?

YakovL
  • 7,557
  • 12
  • 62
  • 102
DEV1205
  • 352
  • 1
  • 6
  • 18

2 Answers2

15

Take a look on this snippet, i think it will help you

under the vis canvas you will see a PNG image. you can right click this image and save it. (or you can save it in any other standard way)

Good Luck.

// create an array with nodes
  var nodes = new vis.DataSet([
    {id: 1, label: 'Node 1'},
    {id: 2, label: 'Node 2'},
    {id: 3, label: 'Node 3'},
    {id: 4, label: 'Node 4'},
    {id: 5, label: 'Node 5'}
  ]);

  // create an array with edges
  var edges = new vis.DataSet([
    {from: 1, to: 3},
    {from: 1, to: 2},
    {from: 2, to: 4},
    {from: 2, to: 5}
  ]);

  // create a network
  var container = document.getElementById('mynetwork');
  var data = {
    nodes: nodes,
    edges: edges
  };
  var options = {};
  var network = new vis.Network(container, data, options);

  network.on("afterDrawing", function (ctx) {
    var dataURL = ctx.canvas.toDataURL();
    document.getElementById('canvasImg').src = dataURL;
  });
#mynetwork {
      width: 600px;
      height: 400px;
      border: 1px solid lightgray;
    }

    p {
      max-width: 600px;
    }
<!doctype html>
<html>
<head>
  <title>Network | Basic usage</title>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.20.0/vis.min.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.20.0/vis.min.css" rel="stylesheet" type="text/css"/>
</head>
<body>

<div id="mynetwork"></div>
<pre id="eventSpan"></pre>
<img id="canvasImg" alt="Right click to save me!">



</body>
</html>
TERMIN
  • 824
  • 8
  • 18
  • 1
    In case of web pages, mostly it is not advisable to use right click. So need to find another way. – DEV1205 Aug 21 '17 at 10:55
  • @DEV1205 You can use a hidden link with the image src as href, create a button that by clicking on it, it will click the hidden link. – TERMIN Aug 24 '17 at 23:17
  • what is `ctx`? [How can this code run without having `ctx` be defined?](https://stackoverflow.com/q/69874023/3416774) – Ooker Nov 07 '21 at 15:51
  • @Ooker ctx is the canvas context, and it is being given by the event handler. – TERMIN Apr 24 '22 at 11:58
0

To make it a button:

network.on("afterDrawing", function(ctx) {
  var dataURL = ctx.canvas.toDataURL();
  document.getElementById('canvasImg').href = dataURL;
})
<input type="button" value="Download image" onclick="document.getElementById('canvasImg').click();">
<a id="canvasImg" download="filename"></a>
Ooker
  • 1,969
  • 4
  • 28
  • 58