dhotson / springy

A force directed graph layout algorithm in JavaScript
http://getspringy.com
MIT License
1.88k stars 240 forks source link

Update node or edge color data after it has been initially rendered #78

Closed thurt closed 8 years ago

thurt commented 9 years ago

Hello again.

How could I go about updating the color data of nodes and edges after they have been added and rendered? It is clear to me how I can specify a color when adding a node or edge, but I do not see how to specify a new color for an existing node or edge. I basically wrote a shortest path function and I would like to update my directed graph to show the shortest path in a different color.

Thanks for any suggestions

thurt commented 8 years ago

So I have figured out a way to do this. I created a modifyColor function which accepts as strings a source node name, a target node name, and a color. I attached the function to the Springy.Graph.prototype.

The function searches through the this.edges property of the graph instance and finds the first edge having the same source node name and target node name. It then takes the edge it found and assigns its data.color property to the new color.

Springy.Graph.prototype.modifyColor = function(source_label, target_label, new_color) {
  return this.edges.some(edge => {
    if (edge.source.data.label === source_label && edge.target.data.label === target_label) {
      edge.data.color = new_color
      return true
    }
  })
}

This was much easier to do after figuring out the internal representation of an edge and node. I think documentation could be improved by explaining the internal representation of an edge and node as well as how things are organized in the basic properties like this.edges and this.adjacency.

There are lots of possible uses for graphs so I think many people will want to extend Springy's functionality in their own use case. But better documentation on how to go about extending Springy would help a lot.

Also better explanation of the data object--are there other built-in properties besides label and color??

thurt commented 8 years ago

Another note I just discovered: It appears I have to call this.notify() in order to update the canvas. Otherwise, the canvas graphics will not update until I move my mouse over the canvas and/or interact with the canvas.

Springy.Graph.prototype.modifyColor = function(source_label, target_label, new_color) {
  return this.edges.some(edge => {
    if (edge.source.data.label === source_label && edge.target.data.label === target_label) {
      edge.data.color = new_color
      this.notify()
      return true
    }
  })
}