2016-10-17 6 views
1

Привет, я хотел бы узнать, как оживить построение графика в Cytoscape.js. Для меня это означает, что пользователь выберет алгоритм компоновки, а затем, начиная с корневого узла, ребро будет расти от узла и в конечном итоге окажется в направлении следующего узла на графике, тогда этот узел будет расти от небольшого точка, и процесс повторяется. В конечном итоге это приведет к анимации всего построенного графика. Я думаю, что это как раз противоположность Images and Breadthfirst Layout Demo.Анимация построения графика в Cytoscape.js

Может ли кто-нибудь помочь мне разобраться в стратегии для этого? Я думаю, мне нужно развернуть безгласный график с моим списком узлов и использовать эти позиции для отображения анимаций в главном графике, отображаемом в контейнере html.

спасибо за любую помощь

ответ

1

Если у вас есть на инициализации всех элементов, просто положить их все в графике. Вы можете сначала их скрывать со своей таблицей стилей, и вы можете показывать их один за другим с анимацией.

Я бы использовал .animation(), а не .animate(), потому что вы можете использовать возвращенный объект animation и его обещание играть. Вы можете просто создать цепочку обещаний в качестве временной шкалы.

+0

спасибо, это имеет смысл, я дам ему шанс – Boo

0

Вот что я в итоге использовал, он будет работать лучше, используя обещание игры, поскольку maxkfranz предлагает вместо задержки.

/****************************************************************************************************  
* https://gist.github.com/maxkfranz/aedff159b0df05ccfaa5 
* method will animate the graph building, from parent to child 
* 
*/ 
animateGraphBuilding = function(nodes){ 

    var delay = 0;  
    var size = nodes.length; 
    var duration = (200000/size); 
    mod = $('#animationSpeed').val()/2; 
    if(mod < 1){ 
     mod = 1; 
     $('#animationSpeed').val(mod); 
    }else if(mod > 100){ 
     mod = 100; 
     $('#animationSpeed').val(mod); 

    } 

    duration /= mod; 

    var visitedMap = {};//used to ensure nodes are only animated once 

    for(var index = 0; index < size; ++index){ 
     visitedMap[nodes[index].data('id')] = 0; 
    } 
    var nodesCopy = nodes.clone();//store original rendered positions 

    //loop through the list of nodes and then, 
    //Find connected nodes and then, 
    //loop through connected nodes and animated from parent to original position 
    for(var i = 0; i < nodes.length; ++i){ 
     var cNode = nodes[i];     
     var nextNodes = cNode.connectedEdges(
       function(){ 
        return this.source().same(cNode); 
       } 
      ).targets();                   

     for (var index = 0; index < nextNodes.length; ++index){ 
      var nNode = nextNodes[index]; 

      (function(currentNode, x, copyNode, nextNode){   

       if(nextNode != null && x != 0 && visitedMap[nextNode.data('id')] < 1){ 
        ++visitedMap[nextNode.data('id')]; 
        //console.log('currentNode: ' + currentNode.data('id')+ ', x: ' + x + ', nextNode: ' + nextNode.data('id')); 

        var position = nextNode.renderedPosition();     
        nextNode.renderedPosition(copyNode.renderedPosition());   

        nextNode.delay(delay, function(){ 
         nextNode.style("visibility", "visible");       
        }).animate( {     
          renderedPosition: position //to this position        
         }, { 
          duration: duration, 
          complete: function(){/*do nothiing*/} 
         }                 
        );     
       }else if (nextNode != null && visitedMap[nextNode.data('id')] < 1){ 

        ++visitedMap[nextNode.data('id')]; 
        var position = nextNode.renderedPosition();     
        nextNode.renderedPosition(copyNode.renderedPosition());   

        nextNode.delay(delay, function(){ 
         currentNode.style("visibility", "visible"); //show the root node 
         nextNode.style('visibility', 'visible');      
        }).animate( {     
          renderedPosition: position,//to this position        
         }, { 
          duration: duration, 
          complete: function(){/*do nothing*/}      
         }          
        );           
       }   

       delay += duration; 

      })(cNode, i, nodesCopy[i], nNode);      
     } //end inner for, iterates through children nodes 
    } // end of outter for, iterates through all nodes     
}; 
Смежные вопросы