GithubHelp home page GithubHelp logo

ngraph.pixi's Introduction

ngraph.pixi

This is a 2d graph renderer which uses PIXI.js as a rendering engine.

build status

Example

This code will render interactive graph:

  // let's create a simple graph with two nodes, connected by edge:
  var graph = require('ngraph.graph')();
  graph.addLink(1, 2);

  // Create a pixi renderer:
  var pixiGraphics = require('ngraph.pixi')(graph);

  // And launch animation loop:
  pixiGraphics.run();

To run it, please refer to example folder.

install

With npm do:

npm install ngraph.pixi

To compile (or browserify) local examples run:

npm start

Customization

ngraph.pixi allows you to customize various aspects of graph appearance

Nodes/Link

When working with ngraph.graph each node may have associated data. This data is considered a data model of a node. ngraph.pixi lets clients convert associated data model into UI model for node (createNodeUI()) or link (createLinkUI()).

Results of these methods are then used to actually render a node (renderNode()) or a link (renderLink()).

// add two nodes with associated data model
graph.addNode('user1', {sex: 'male'});
graph.addNode('user2', {sex: 'female'});

// Construct UI model for node:
pixiGraphics.createNodeUI(function (node) {
  return {
    width: 2 + Math.random() * 20,
    // use settings from node's data
    color: node.data.sex === 'female' ? 0xFF0000 : 0x0000FF
  };
});

// tell pixi how we want to render each UI model:
pixiGraphics.renderNode(function (nodeUIModel, ctx) {
  ctx.lineStyle(0);
  ctx.beginFill(nodeUIModel.color);
  var x = nodeUIModel.pos.x - nodeUIModel.width/2,
      y = nodeUIModel.pos.y - nodeUIModel.width/2;

  ctx.drawRect(x, y, nodeUIModel.width, nodeUIModel.width);
});

There are several reasons for such separation of concerns. One is performance: By constructing UI model once we are saving CPU cycles at rendering time. Another reason for separation - you can have multiple renderers render the same graph without interfering with each other.

Physics

You can change default physics engine parameters by passing physics object inside settings:

  var createPixiGraphics = require('ngraph.pixi');
  var pixiGraphics = createPixiGraphics(graph, {
    physics: {
      springLength: 30,
      springCoeff: 0.0008,
      dragCoeff: 0.01,
      gravity: -1.2,
    }
  })

To read more information about each of these and even more properties, please refer to physics engine documentation.

What is missing?

This library was created as part of ngraph project. If you like PIXI and want to help with graph rendering, your contribution is absolutely welcomed and appreciated. Here are just some things which could be done better:

  • Renderer currently works with PIXI.Graphics, which does not let rendering custom text on the screen
  • PIXI.Graphics has decent pressure on garbage collector, since all primitives are rerendered on each frame. This can be improved by implementing custom PIXI.DisplayObject - more info
  • Mouse events are not exposed externally from the renderer. It will be nice to let clients of this library to react on user actions.
  • While touch event is supported by PIXI.js it needs to be added to the renderer.
  • Need methods like pan/zoom to be exposed via API

license

MIT

ngraph.pixi's People

Contributors

anvaka avatar nicky1038 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ngraph.pixi's Issues

Background color

Is there any way to change the renderer background color? Looking at the source, I found the background property in the settings object ⬇️

ngraph.pixi/index.js

Lines 8 to 10 in 6322615

settings = merge(settings, {
// What is the background color of a graph?
background: 0x000000,

but, apparently, it is currently ignored. Maybe setting the backgroundColor property of the renderer could fix this issue ?

var renderer = PIXI.autoDetectRenderer(width, height, null, false, true);
+ renderer.backgroundColor = settings.background

BTW, thanks for this nice integration! 😃

Asynchronously adding node's decorators (images, labels)

In #1 examples shown how to create labels and add thumbnails to nodes.

I was able to customise nodes by creating sprite of thumbnails when initialising the node.

However, with this design I have to wait that images are downloaded, and so they are no more asynchrously attached.

Could you suggest a better design so to that the graph can be rendered without waiting, and thumbnails are added once ready?

upgraded to pixi 4.5.4 - clashes with eventify

I upgrade packages.json to last PIXI.

Build clashes with eventify.
Commenting out eventify(publicApi); in physicsSimulator allows to build.

What does eventify do?

Should I expect which differences ?

Дальнейшее развитие темы

Здравствуйте,
хочу проинформировать вас, что планирую развить вашу разработку ngraph.pixi.

В частности мне нужно решить задачу отрисовки больших графов (> 5К узлов) с приемлемым FPS и при этом иметь под рукой достаточно широкие возможности по рисованию. Пока выбор остановился на Pixi, как вроде бы единственного средства по работе с граф. примитивами на WebGL. В текущей реализации ngraph.pixi на больших графах FPS крайне мал и у меня он в районе 5. Причем мне показалось 3-я версия даже чуть медленнее. Тогда как на Sigma.js ничего не тормозит, но там дальше узлов в виде кружочков не уедешь - придется рисовать все с нуля на голом WebGL.

У меня пока такие планы:

  • Сделать, чтобы узлы рендерились как спрайты, используя ParticleContainer, при этом нужно, чтобы при зуме они перерендеривались в спрайты на более высокое разрешение. При зуме можно использовать throttle или debounce техники.
  • Добавить возможность навешивания событий мышки на узлы / ребра.
  • Возможность отрисовки подписей (на узлах и ребрах)

Пока форк лежит вот здесь https://github.com/fobdy/ngraph.pixi. Я там несколько ранее обновился до 3-ей версии Pixi. Если смотреть на отличия от вашей версии, то я добавил поддержку pan и antialias. Т.к. pan вроде после обновления до v3 ломается. Еще правда с mouse origin надо разобраться - он все в центр зумит, а надо в точку относительно мышки. Еще не нравится какое-то дерганье при зуме - надо посмотреть, чего изменить там.

Если у вас есть какие-то советы или рекомендации дабы направить меня в нужное русло, рад буду услышать.

initPhysics crash with graphs with no links

I found a bug in initPhysics if there is a graph with no links.

To reproduce it, replace:

var graph = require('ngraph.generators').balancedBinTree(6);

with:

var graph = require('ngraph.generators').balancedBinTree(6);
  graph.clear();
  graph.addNode(1);

same problem with :

  var createGraph = require('ngraph.graph');
  var graph = createGraph();
  graph.addNode(1);

Instead:

  var Viva = require('vivagraphjs');
	var graph = Viva.Graph.graph();
	graph.addNode(1);

works fine and you can then pass the graph to Pixi as well.

I could not spot the reason of the error, I tried my best.
I just found that a node object is initialised with properties:
node.id
node.data // stuff
node.links = null
and maybe the node.links = null clash with the loop to compute springForce of missing objects (should it be links = [] ?)

bundle.js:3142 Uncaught TypeError: Cannot read property 'length' of null
    at nodeMass (bundle.js:3142)
    at updateBodyMass (bundle.js:3111)
    at initBody (bundle.js:3044)
    at bundle.js:3022
    at Object.objectKeysIterator [as forEachNode] (bundle.js:3992)
    at initPhysics (bundle.js:3021)
    at createLayout (bundle.js:2869)
    at module.exports (bundle.js:58)
    at Object.module.exports.main (bundle.js:14)
    at onload ((index):11)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.