Setup & initialization
This chapter will introduce how to build a basic Cytoscape.js graph visualization application using pure JavaScript (Vanilla JS).
Open a standalone demo to switch between the live preview and its source files:
Basic Environment Configuration
CDN Integration
Include Cytoscape.js via CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.28.1/cytoscape.min.js"></script>NPM Installation
If you’re using Node.js, you can install via NPM:
npm install cytoscapeThen import in your code:
import cytoscape from "cytoscape";Page Structure
Create a basic HTML structure with a container for the graph:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Cytoscape.js Basic Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.28.1/cytoscape.min.js"></script>
<style>
#cy {
width: 600px;
height: 400px;
border: 1px solid #ccc;
margin: 20px auto;
/* Important: container must have a fixed height */
position: relative;
}
</style>
</head>
<body>
<div id="cy"></div>
</body>
</html>Initialize Graph Instance
Add the following JavaScript code at the bottom of the HTML file:
const cy = cytoscape({
// Container element
container: document.getElementById("cy"),
// Elements in the graph (nodes and edges)
elements: [
// Sample data
{ data: { id: "a" } }, // Node a
{ data: { id: "b" } }, // Node b
{ data: { id: "ab", source: "a", target: "b" } }, // Edge from a to b
],
// Style definitions
style: [
{
selector: "node",
style: {
"background-color": "#666",
label: "data(id)",
},
},
{
selector: "edge",
style: {
width: 2,
"line-color": "#999",
"curve-style": "bezier", // Important: set edge curve style
},
},
],
// Layout configuration
layout: {
name: "grid", // Grid layout
rows: 2, // Optional: specify number of rows
cols: 2, // Optional: specify number of columns
},
// Performance-related configuration
minZoom: 0.1, // Minimum zoom level
maxZoom: 10, // Maximum zoom level
wheelSensitivity: 0.2, // Mouse wheel sensitivity
pixelRatio: "auto", // Pixel ratio, can be a number or 'auto'
});Core Configuration Explanation
Basic Configuration Parameters
-
container: Specifies which DOM element the graph will render in- Must be a DOM element
- Container must have a fixed height
- Recommended to set
position: relative
-
elements: Defines nodes and edges in the graph- Nodes must have unique
ids - Edges must have
sourceandtarget - Can include custom data
- Nodes must have unique
-
style: Defines visual styles for elements- Uses selectors to target elements
- Supports various visual properties
- Can reference element data
-
layout: Specifies the graph layout algorithm- Multiple built-in layout algorithms
- Each layout has specific parameters
- Can switch layouts dynamically
Performance Optimization Configuration
-
Rendering Optimization
textureOnViewport: Use textures on viewport (suitable for large graphs)pixelRatio: Control rendering resolutionhideEdgesOnViewport: Hide edges during panning
-
Interaction Optimization
minZoomandmaxZoom: Limit zoom rangewheelSensitivity: Control scroll wheel sensitivityautoungrabify: Disable node draggingautounselectify: Disable element selection
-
Memory Optimization
- Use
cy.destroy()to clean up unused instances - For large graphs, consider using
headless: truefor background calculations
- Use
Debugging and Development
-
Development Tools
// Access instance in console window.cy = cy; -
Event Listening
cy.on("ready", () => { console.log("Graph initialization complete"); }); -
Error Handling
try { const cy = cytoscape(options); } catch (error) { console.error("Initialization failed:", error); }
Best Practices
-
Container Setup
- Ensure container has clear dimensions
- Use
position: relative - Consider responsive design
-
Initialization Timing
- Initialize after DOM is loaded
- Use
DOMContentLoadedevent - Ensure dependencies are loaded
-
Performance Considerations
- Set appropriate
minZoomandmaxZoom - Consider performance options for large graphs
- Mind memory management and cleanup
- Set appropriate
-
Development Tips
- Use browser developer tools for debugging
- Keep code modular
- Implement proper error handling
Start with the workspace
Use CausalWorkspace for the model viewer and CausalEditor for authoring. They own the Cytoscape instance. Keep native initialisation for standalone graphs; do not create a second instance inside a framework-owned container.