获取集合内平行边并设置独立颜色,代码执行异常求助
Hey there! Let's figure out why your code ends up coloring every edge instead of just the parallel ones, and fix it to assign unique colors to each set of parallel edges.
What's Going Wrong With Your Current Code?
Your line cy.elements().parallelEdges() has two key issues that lead to all edges being styled:
cy.elements()includes nodes AND edges: When you callparallelEdges()on a node, it returns an empty set—but when called on edges, it grabs their parallel counterparts. If every edge in your graph has a parallel match, the combined result ends up being every edge in the graph.- How
parallelEdges()works for collections: For a collection of edges,.parallelEdges()returns all edges that are parallel to any edge in the collection. So if you pass every edge into it, you'll get back every edge that has a parallel pair (which, in your case, seems to be all edges).
Fix Step-by-Step: Target Parallel Edge Groups & Assign Unique Colors
To get the behavior you want—grouping parallel edges and giving each group its own color—follow these steps:
1. Target Only Edges (Skip Nodes)
First, narrow down your selection to just edges instead of all elements:
const allEdges = cy.edges();
2. Group Parallel Edges Together
We need to cluster edges into groups where each group consists of edges that are parallel to each other. Here's how to do that:
const parallelEdgeGroups = []; const processedEdgeIds = new Set(); allEdges.forEach(edge => { // Skip if we've already processed this edge if (processedEdgeIds.has(edge.id())) return; // Get all edges parallel to this one, plus the edge itself // Set `directed: true` if you want to only match edges with the same source/target direction const group = edge.parallelEdges({ directed: false }).add(edge); parallelEdgeGroups.push(group); // Mark all edges in this group as processed group.forEach(e => processedEdgeIds.add(e.id())); });
3. Animate Each Group With a Unique Color
Now that we have our groups, we can assign distinct colors to each one. We'll cycle through a list of colors to keep things simple:
// Customize this color list to your liking const colorPalette = ['coral', 'skyblue', 'limegreen', 'orange', 'mediumpurple']; parallelEdgeGroups.forEach((group, index) => { // Cycle through the color palette if there are more groups than colors const selectedColor = colorPalette[index % colorPalette.length]; group.animate( { style: { 'line-color': selectedColor, 'width': '10px' } }, { duration: 1000 } ); });
How to Verify the Issue
If you want to confirm why your original code affected all edges, run these console logs to compare counts:
console.log('Parallel edges returned by your code:', cy.elements().parallelEdges().size()); console.log('Total edges in the graph:', cy.edges().size());
If the numbers match, that means every edge in your graph has a parallel pair—so the collection returned by parallelEdges() includes every edge.
内容的提问来源于stack exchange,提问作者Asad Ali Khan

