Tips for saving a Cytoscape.js diagram as an image

Currently, I am diving into learning Cytoscape.js. After successfully creating an HTML file with a basic graph, I attempted to export the graph to an image using the following code:

var png64 = cy.png();

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

This resulted in an error:

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

I came across a related post about "Uncaught TypeError: Cannot read property 'value' of null" on Stack Overflow, but the explanation was a bit confusing. It seems like the issue might be due to the absence of an element declared with the id #png-eg. When I tried substituting it with other elements like cy (to display the graph), a, b, ab (representing nodes and edges), only cy did not throw an error. However, I still couldn't figure out where the image was located.

I even attempted adding this element

<img id="png-eg" src="">
in the body, but the null error persisted. Surprisingly, if I exclude the cy.png() from the script and enter it directly in the console, a different error occurs:
Uncaught DOMException: String contains an invalid character
.

Upon seeing the line window.cy in the example, I decided to execute it in the console. The result was: Object { _private: {…} }

Answer №1

If you want to display a snapshot of a graph rendered using Cytoscape, follow these steps (ensure that the DOM is fully loaded before querying 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'),
  // add any other configurations needed
})

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

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

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

By executing this code, it will generate a new image element with the base64 encoded PNG representation from Cytoscape. This image will be appended to the DOM, allowing you to view the graph snapshot within the image tag.

You can try out the full example on StackBlitz.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Identify modifications to properties in Angular

What is the most effective method for responding to property changes within a component? I am seeking a solution that will trigger a specific function every time a property in a component is altered. Consider the following example with a single component: ...

Is it possible to utilize a pre-existing JS "package" with Node.JS?

Recently, I decided to convert my existing JS code into an NPM package for easier distribution. The package is called "my-pkg" and includes the following files: my-pkg.js package.json my-pkg.js function ping() { console.log("Hi!"); } package.json ...

Tips for exploring electron without launching additional windows

Is there a way to navigate between HTML pages within the same window without opening multiple windows in Electron? ...

Transforming jQuery into vanilla JavaScript in order to create a customized dropdown select functionality

I am struggling with converting jQuery code to pure JavaScript for a custom select element. https://codepen.io/PeterGeller/pen/wksIF After referencing the CodePen example, I attempted to implement it with 3 select elements. const select = document.get ...

Utilize the key as the value for options within an object iteration in Vue.js

I have an object called colors, which stores color names: { "RD": "Red", "BL": "Blue", "GR": "Green", "YW": "Yellow" } In my dropdown menu, I'm generating options for each color in the colors object: <select v-model="colors"> <op ...

Leverage the router through the getServerSideProps method

My goal is to automatically redirect the user to the login page if their token has expired. I need to handle this in the getServerSideProps method where I make a request to the server for data. If the request is unauthorized, I want to use the useRouter ho ...

Here is a method to display a specific string in the mat-datepicker input, while only sending the date in the backend

enter image description hereIn this code snippet, there is a date input field along with a Permanent button. The scenario is that when the Permanent button is clicked, it should display "Permanent" in the input UI (nativeElements value), but the value bein ...

Encountered a failure while loading modules in AngularJS

When I tried opening the index.html page using Chrome, I encountered an error stating that the correct modules could not be found. Uncaught SyntaxError: Unexpected token < angular.js:1 Uncaught SyntaxError: Unexpected token < controller.js:1 ...

Tips on scrolling the web page until the desired web element is visible and carrying out necessary tasks

When searching for input, multiple table data is retrieved. A "show as text link" is present in different table rows that needs to be clicked. I wrote a code that works fine in IE on one machine but does not work on a different machine due to variations i ...

Issue: AngularJS modal not appearing when utilizing partial for template URLExplanation: The Angular

I am having trouble with a modal in a partial file that is supposed to be loaded into my main view using an ng-include tag. However, the template cannot be found and I do not see it being loaded in the console or network tab. The error message I receive is ...

Vuetify's <v-text-field> feature automatically clears the input after selecting a result from Google Maps autocomplete

A dilemma I'm facing is with a page that has a <v-text-field> containing GoogleMaps autocomplete. The problem arises when Vuetify clears the input once an address is selected by the user. I have discovered that this complication is connected to ...

What is the best method to send a HTTP request (specifically for scraping) to an Angular2 website?

I am attempting to utilize a node server to extract data from an angular2 application. However, the issue I am encountering is that the response I receive is just the index.js file, which essentially represents the "loading..." section of the webpage. My ...

Steps to create a conditional AJAX request triggered by the onbeforeload event depending on the value of a variable

My website script tracks user login status in real time using "onbeforeunload", ajax, and logout.php. This method updates the MySQL database with a value of 1 or 0 to indicate if a user is logged in. Unlike monitoring cookies, this approach allows accurate ...

What is the best way to save a beloved pet for a user who is signed in?

Is there a way to store a favorite pet for a logged-in user using React and Express? I am currently retrieving pets from an API and using PostgreSQL as the database. const favPetDetails = { id, name, media, breeds, location, dista ...

Creating a ListView in React Native and utilizing the CloneWithRow method with an object instead of an

When retrieving data from a webservice, I am able to work with JSON arrays without any issues. WebServiceHandler.get('http:/api.local/stock',{},{) .then((val)=>{ this.setState({ dataSource: this.state.dataSou ...

Forms for uploading and submitting multiple files

On my single page, I have several file upload forms that are generated in a loop. The issue is that the first file upload control works fine, but the others do not. <div> <form action="/docs/1046/UploadDocument?Id=1046&amp;propertyTypeId ...

Troubleshooting the issue: Node.js application unable to utilize Mongodb's $addToSet functionality

I'm having an issue with mongo's $addToSet function not properly adding a Store to my stores array (where I have commented out seemed to work), resulting in duplicate IDs. Can anyone help me identify my mistake and suggest a solution? Thank you. ...

Executing a javascript function numerous times

Here are a few examples: <div class="statement">text goes here</div> <div class="response"><input type="text" id="amount1" style="border: 0; color: #f6931f; font-weight: bold;" /></div> <div id="sli ...

What is the best way to retrieve data attributes from multiple div elements that share the same class name?

I have multiple div elements with the same class name. I want to extract the data attribute from these div's. I have tried some code and managed to get the result. However, I am unsure if this is the best approach for retrieving data("cartid"). Any as ...

Trouble with Title Updating in Next.js and Tailwind CSS Project

I am currently facing an issue with the title of my website not updating, even though I am using next/Head and have included the title tag. "use client"; import Head from 'next/head'; import { BsFillMoonStarsFill } from 'react-ico ...