How to export a Cytoscape.js graph to image?

Viewed 449

I am learning Cytoscape.js. I successfully make a HTML file containing this basic graph. I try to export the graph to image using:

var png64 = cy.png();

// put the png data in an img tag
document.querySelector('#png-eg').setAttribute('src', png64);) 

and get the error

Uncaught TypeError: document.querySelector(...) is null
    <anonymous> debugger eval code:1
debugger eval code:1:10

There is this post Uncaught TypeError: Cannot read property 'value' of null but I don't understand it. I suspect it's simply that there is no declared element with id #png-eg. But when I replace that with other declared elements with id – which are cy (to display the graph), a, b, ab (the nodes and edge) – the only element that doesn't yield the error is cy. But even then I don't know where the image locates.

I tried add this element <img id="png-eg" src=""> in the body, but it still doesn't work. The null error still happens. (But if I don't include the cy.png() in the script but type in the console, the error is Uncaught DOMException: String contains an invalid character).

In the example there is a line window.cy, so I try to run that in the console. I get Object { _private: {…} }

1 Answers

If you have the following (make sure the DOM is loaded before trying to query for elements):

HTML:

<div id="cy"></div>

<button>Render PNG</button>

CSS:

#cy {
  width: 320px;
  height: 320px;
}

JS:

const cy = cytoscape({
  container: document.getElementById('cy'),
  // and the rest of the example you already have
})

const btn = document.querySelector('button');

btn.addEventListener('click', () => {
  const base64URI = cy.png();
  const img = document.createElement('img');
  img.src = base64URI;

  document.body.appendChild(img);
});

This will create a new image element and make its source equal to the base64 PNG representation exported by Cytoscape. Then the element will be added to the DOM and you can see the snapshot of the graph rendered inside the image tag.

You can see the whole example on StackBlitz.

Related