IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JavaScript Discussion :

Implémentation graphe orienté


Sujet :

JavaScript

  1. #1
    Futur Membre du Club
    Profil pro
    Inscrit en
    Octobre 2011
    Messages
    11
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 11
    Points : 7
    Points
    7
    Par défaut Implémentation graphe orienté
    Bonjour,

    Je cherche une solution pour dessiner des graphes orientés (de ce type : https://www.qwant.com/?q=graphe%20or...a028888d362855) de façon esthétique, en récupérant les data depuis un json / variable js ou autre.

    Il faudrait aussi que les points soient cliquables et permettent de déployer du contenu qui y est rattaché.

    Avez-vous une idée / connaissez vous une bibliothèque adaptée ?

  2. #2
    Rédacteur

    Avatar de danielhagnoul
    Homme Profil pro
    Étudiant perpétuel
    Inscrit en
    Février 2009
    Messages
    6 389
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 73
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant perpétuel
    Secteur : Enseignement

    Informations forums :
    Inscription : Février 2009
    Messages : 6 389
    Points : 22 933
    Points
    22 933
    Billets dans le blog
    125

    Blog

    Sans l'analyse et la conception, la programmation est l'art d'ajouter des bogues à un fichier texte vide.
    (Louis Srygley : Without requirements or design, programming is the art of adding bugs to an empty text file.)

  3. #3
    Futur Membre du Club
    Profil pro
    Inscrit en
    Octobre 2011
    Messages
    11
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 11
    Points : 7
    Points
    7
    Par défaut
    Bonjour,

    T'abord merci, d3 semble correspondre parfaitement à ce que je voulais faire.

    Cela dit je rencontre quelques problèmes

    Voici donc ce que j'ai fait:
    CSS
    Code css : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    svg {
      background-color: #FFF;
      cursor: default;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      -o-user-select: none;
      user-select: none;
    }
     
    svg:not(.active):not(.ctrl) {
      cursor: crosshair;
    }
     
    path.link {
      fill: none;
      stroke: #000;
      stroke-width: 4px;
      cursor: default;
    }
     
    svg:not(.active):not(.ctrl) path.link {
      cursor: pointer;
    }
     
    path.link.selected {
      stroke-dasharray: 10,2;
    }
     
    path.link.dragline {
      pointer-events: none;
    }
     
    path.link.hidden {
      stroke-width: 0;
    }
     
    circle.node {
      stroke-width: 1.5px;
      cursor: pointer;
    }
     
    circle.node.reflexive {
      stroke: #000 !important;
      stroke-width: 2.5px;
    }
     
    text {
      font: 12px sans-serif;
      pointer-events: none;
    }
     
    text.id {
      text-anchor: middle;
      font-weight: bold;
    }

    HTML
    Code html : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <!DOCTYPE html>
    <html>
       <head>
          <meta charset="utf-8">
          <title>Graphe de test</title>
          <link rel="stylesheet" href="styles.css">
       </head>
     
       <body>
       </body>
     
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
       <script src="http://d3js.org/d3.v3.min.js"></script>
       <script src="graphe.js"></script>
    </html>
    JS
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    // set up SVG for D3
    var width  = $(window).width() - 50,
        height = $(window).height() - 50,
        colors = d3.scale.category10();
     
    var svg = d3.select('body')
      .append('svg')
      .attr('oncontextmenu', 'return false;')
      .attr('width', width)
      .attr('height', height);
     
    // set up initial nodes and links
    //  - nodes are known by 'id', not by index in array.
    //  - reflexive edges are indicated on the node (as a bold black circle).
    //  - links are always source < target; edge directions are set by 'left' and 'right'.
    var nodes = [
        {id: "Concepteur", reflexive: false},
        {id: "main", reflexive: false },
        {id: "poigne", reflexive: false},
        {id: "bois", reflexive: false},
        {id: "metal", reflexive: false},
        {id: "plastique", reflexive: false},
        {id: "balayage", reflexive: false},
        {id: "fibres végétales", reflexive: false},
        {id: "fibres synthéthiques", reflexive: false},
        {id: "Dépoussiérer", reflexive: false}
      ],
      lastNodeId = 6,
      links = [
        {source: nodes[0], target: nodes[1], left: false, right: true },
        {source: nodes[1], target: nodes[2], left: false, right: true },
        {source: nodes[2], target: nodes[3], left: false, right: true },
        {source: nodes[2], target: nodes[4], left: false, right: true },
        {source: nodes[2], target: nodes[5], left: false, right: true },
        {source: nodes[3], target: nodes[6], left: false, right: true },
        {source: nodes[4], target: nodes[6], left: false, right: true },
        {source: nodes[5], target: nodes[6], left: false, right: true },
        {source: nodes[6], target: nodes[7], left: false, right: true },
        {source: nodes[6], target: nodes[8], left: false, right: true },
        {source: nodes[7], target: nodes[9], left: false, right: true },
        {source: nodes[8], target: nodes[9], left: false, right: true }
      ];
     
    // init D3 force layout
    var force = d3.layout.force()
        .nodes(nodes)
        .links(links)
        .size([width, height])
        .linkDistance(50)
        .charge(-2500)
        .on('tick', tick);
     
    // define arrow markers for graph links
    svg.append('svg:defs').append('svg:marker')
        .attr('id', 'end-arrow')
        .attr('viewBox', '0 -5 10 10')
        .attr('refX', 6)
        .attr('markerWidth', 3)
        .attr('markerHeight', 3)
        .attr('orient', 'auto')
      .append('svg:path')
        .attr('d', 'M0,-5L10,0L0,5')
        // arrow colors
        .attr('fill', '#000');
     
    svg.append('svg:defs').append('svg:marker')
        .attr('id', 'start-arrow')
        .attr('viewBox', '0 -5 10 10')
        .attr('refX', 4)
        .attr('markerWidth', 3)
        .attr('markerHeight', 3)
        .attr('orient', 'auto')
      .append('svg:path')
        .attr('d', 'M10,-5L0,0L10,5');
     
    // line displayed when dragging new nodes
    var drag_line = svg.append('svg:path')
      .attr('class', 'link dragline hidden')
      .attr('d', 'M0,0L0,0');
     
    // handles to link and node element groups
    var path = svg.append('svg:g').selectAll('path'),
        circle = svg.append('svg:g').selectAll('g');
     
        // mouse event vars
    var selected_node = null,
        selected_link = null,
        mousedown_link = null,
        mousedown_node = null,
        mouseup_node = null;
     
     
    // on node click.
    function click(d) {
       window.alert("toto");
    }
    // update force layout (called automatically each iteration)
    function tick() {
      // draw directed edges with proper padding from node centers
      path.attr('d', function(d) {
        var deltaX = d.target.x - d.source.x,
            deltaY = d.target.y - d.source.y,
            dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY),
            normX = deltaX / dist,
            normY = deltaY / dist,
            sourcePadding = d.left ? 17 : 12,
            targetPadding = d.right ? 17 : 12,
            sourceX = d.source.x + (sourcePadding * normX),
            sourceY = d.source.y + (sourcePadding * normY),
            targetX = d.target.x - (targetPadding * normX),
            targetY = d.target.y - (targetPadding * normY);
        return 'M' + sourceX + ',' + sourceY + 'L' + targetX + ',' + targetY;
      });
     
      circle.attr('transform', function(d) {
        return 'translate(' + d.x + ',' + d.y + ')';
      });
    }
     
    // update graph (called when needed)
    function restart() {
      // path (link) group
      path = path.data(links);
     
     
     
     
      // add new links
      path.enter().append('svg:path')
        .attr('class', 'link')
        .classed('selected', function(d) { return d === selected_link; })
        .style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
        .style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; })
        .on('mousedown', function(d) {
          if(d3.event.ctrlKey) return;
     
          // select link
          mousedown_link = d;
          if(mousedown_link === selected_link) selected_link = null;
          else selected_link = mousedown_link;
          selected_node = null;
          restart();
        });
     
     
      // circle (node) group
      // NB: the function arg is crucial here! nodes are known by id, not by index!
      circle = circle.data(nodes, function(d) { return d.id; });
     
      // update existing nodes (reflexive & selected visual states)
      circle.selectAll('circle')
        .style('fill', function(d) { return (d === selected_node) ? d3.rgb(colors(d.id)).brighter().toString() : colors(d.id); })
        .classed('reflexive', function(d) { return d.reflexive; });
     
      // add new nodes
      var g = circle.enter().append('svg:g');
     
      g.append('svg:circle')
        .attr('class', 'node')
        .attr('r', 12)
        .style('fill', function(d) { return (d === selected_node) ? d3.rgb(colors(d.id)).brighter().toString() : colors(d.id); })
        .style('stroke', function(d) { return d3.rgb(colors(d.id)).darker().toString(); })
        .classed('reflexive', function(d) { return d.reflexive; })
        .on('mouseover', function(d) {
          if(!mousedown_node || d === mousedown_node) return;
          // enlarge target node
          d3.select(this).attr('transform', 'scale(1.1)');
        })
        .on('mouseout', function(d) {
          if(!mousedown_node || d === mousedown_node) return;
          // unenlarge target node
          d3.select(this).attr('transform', '');
        })
        .on('mousedown', function(d) {
          if(d3.event.ctrlKey) return;
     
          // select node
          mousedown_node = d;
          if(mousedown_node === selected_node) selected_node = null;
          else selected_node = mousedown_node;
          selected_link = null;
     
          // reposition drag line
          drag_line
            .style('marker-end', 'url(#end-arrow)')
            .classed('hidden', false)
            .attr('d', 'M' + mousedown_node.x + ',' + mousedown_node.y + 'L' + mousedown_node.x + ',' + mousedown_node.y);
     
          restart();
        })
        .on('mouseup', function(d) {
          if(!mousedown_node) return;
     
          // needed by FF
          drag_line
            .classed('hidden', true)
            .style('marker-end', '');
     
          // check for drag-to-self
          mouseup_node = d;
          window.alert(mouseup_node.id);
     
          // unenlarge target node
          d3.select(this).attr('transform', '');
     
          // add link to graph (update if exists)
          // NB: links are strictly source < target; arrows separately specified by booleans
          var source, target, direction;
          if(mousedown_node.id < mouseup_node.id) {
            source = mousedown_node;
            target = mouseup_node;
            direction = 'right';
          } else {
            source = mouseup_node;
            target = mousedown_node;
            direction = 'left';
          }
     
          var link;
          link = links.filter(function(l) {
            return (l.source === source && l.target === target);
          })[0];
     
          if(link) {
            link[direction] = true;
          } else {
            link = {source: source, target: target, left: false, right: false};
            link[direction] = true;
            links.push(link);
          }
     
          // select new link
          selected_link = link;
          selected_node = null;
          restart();
        });
     
      // show node IDs
      g.append('svg:text')
          .attr('x', 0)
          .attr('y', 25)
          .attr('class', 'id')
          .text(function(d) { return d.id; });
     
      // remove old nodes
      circle.exit().remove();
     
      // set the graph in motion
      force.start();
    }
     
     
     
    // app starts here
    restart();
    Et voici ce que j'obtiens :
    Nom : 404241test.jpg
Affichages : 413
Taille : 28,2 Ko

    Là où ça bloque :
    - j'aimerais que le graphe s'affiche toujours horizontalement, et soit figé
    - pouvoir modifier le diamètre des noeuds
    - ajouter des noeuds qui ne sont attachés à rien mais qui toutefois se positionnent au niveau de l'abscisse d'un noeud désigné.

    Tous vos conseils sont les bienvenus,

    Merci,

Discussions similaires

  1. Implémentation d'un Graphe orienté
    Par Anonymouse dans le forum Entrée/Sortie
    Réponses: 8
    Dernier message: 13/03/2009, 23h18
  2. Application graphes orientés
    Par cashp dans le forum Algorithmes et structures de données
    Réponses: 19
    Dernier message: 03/04/2007, 17h43
  3. Graphe orienté : chemin de longueur k ?
    Par bugmenot dans le forum Algorithmes et structures de données
    Réponses: 8
    Dernier message: 15/12/2005, 17h07
  4. [Images] graphes orientés
    Par Atchoum_002 dans le forum Bibliothèques et frameworks
    Réponses: 4
    Dernier message: 25/10/2005, 16h47

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo