Search code examples
javascriptjquerywebglvivagraphjs

VivagraphJS, WebGL and event listener


I absolutely love Vivagraph JS. Having said that, I've run into a pickle, that is probably WebGL specific.

I'm trying to:

  var graph = Viva.Graph.graph();

  var layout = Viva.Graph.Layout.forceDirected(graph, {
    springLength : 30,
    springCoeff : 0.0003,
    dragCoeff : 0.005,
    gravity : -0.2,
    theta: 0.8
  });

  var graphics = Viva.Graph.View.webglGraphics();
  graphics.node( function( node )
  { 
    node.addEventListener( 'click', function ()
    { 
      console.log( 'clicked node: ' + node.id ); 
    });

    return Viva.Graph.View.webglSquare( 10, color );
  });

  var renderer = Viva.Graph.View.renderer( graph,
  { 
    container  : document.getElementById( 'graph' ),
    graphics : graphics, 
    layout: layout 
  });

  renderer.run();

I've seen a similar example, using the SVG instead. Using WebGL doesn't seem to work:

Uncaught TypeError: Object [object Object] has no method 'addEventListener' 

How can I add an event listener from javascript/jquery to the webgl particle that makes up the node?

Or should I abandon WebGL altogether for my intents and purposes?


Solution

  • WebGL in general does not have built in support for events. VivaGraph provides a wrapper on top of it to let you listen to events. I'm not really happy with its implementation, but it works:

    var events = Viva.Graph.webglInputEvents(webGLGraphics, graph);
    
    events.mouseEnter(function (node) {
        console.log('Mouse entered node: ' + node.id);
    }).mouseLeave(function (node) {
        console.log('Mouse left node: ' + node.id);
    }).dblClick(function (node) {
        console.log('Double click on node: ' + node.id);
    }).click(function (node) {
        console.log('Single click on node: ' + node.id);
    });
    

    You can also check WebGL Input demo for complete example.