Playing with D3.js

Sunday, September 30, 2012 at 5:35 PM

I haven't done much on my Composer project until recently when I came across the javascript library, D3.js. D3 stands for Data-Driven Documents. It's all about efficient binding between data and DOM elements. With just a few hours of work, I was able to create something that takes some JSON and generates a beautiful interactive graph...



I'll leave out all the gory details about how it was generated. The important part is that it was generated from the following JSON...

var json = {
  "component":{
    "id":"myComponent",
    "vertices":[
      {"id":"Cell1", "vertexType":"cell"},
      {"id":"Cell2", "vertexType":"cell"},
      {"id":"Cell3", "vertexType":"cell"},
      {"id":"Cell4", "vertexType":"cell"},
      {"id":"Cell5", "vertexType":"cell"},
      {"id":"Cell6", "vertexType":"cell"},
      {"id":"Connector1", "vertexType":"connector", ioCount:5}
    ],
    "edges":[
      {"source": "Cell1", "target": "Cell2", "type": "connection", "targetConnection": "InputMaster"},
      {"source": "Cell1", "target": "Cell2", "type": "association"},
      {"source": "Cell1", "target": "Cell3", "type": "connection", "targetConnection": "InputInverted"},
      {"source": "Cell1", "target": "Cell4", "type": "connection", "targetConnection": "InputSlave"},
      {"source": "Cell3", "target": "Cell4", "type": "connection", "targetConnection": "InputSlaveInverted"},
      {"source": "Cell4", "target": "Cell5", "type": "connection", "targetConnection": "Input"},
      {"source": "Cell4", "target": "Connector1", "type": "connection", "targetConnection": "Input", "targetIndex": 0},
      {"source": "Cell1", "target": "Connector1", "type": "connection", "targetConnection": "Input", "targetIndex": 1},
      {"source": "Connector1", "target": "Cell6", "type": "connection", "targetConnection": "Input", "sourceIndex": 4}
    ],
    "data":[
    ]
  }
};

The difficult part was making up for the sleep I enjoyed many moons ago in my high school trigonometry class. I had to figure out how to offset those little circles from the centers of the larger circles according to the angle of the line. The math is only simple once you figure out what equations to plug in.

There will still be a lot of work before it becomes useful. I need to be able to add and remove various types of nodes with different representations of them and add/remove connections between them. A component will usually have one or more variables and/or small memory heaps that it is in charge of, so there will need to be a way to manage that. And all aspects of a given component need to be transformed to/from JSON.

0 comments

Post a Comment