How do I show edge labels on graphs?

前端 未结 3 630
感情败类
感情败类 2021-01-03 05:46

I am trying to load a gexf file with sigInst.parseGexf(\'data/test.gexf\').

To create an edge with label I have this line in gexf file:



        
3条回答
  •  生来不讨喜
    2021-01-03 06:29

    All credit goes to @sam2themax - who forked it out. I am just adding the relevant portions to make life easier.

    On sigma.js main library - go to function drawEdge(edge) Add the below lines :

      var p1 = {};
      p1.x = sourceCoordinates[0];
      p1.y = sourceCoordinates[1];
      var p2 = {};
      p2.x = targetCoordinates[0];
      p2.y = targetCoordinates[1];
      drawEdgeLabel(ctx,edge['label'],p1,p2, color);
    

    Create the new method :

      function drawEdgeLabel(ctx, text, p1, p2, color) {
    console.log(text);
    var alignment = 'center';
    var padding = 10;
    
    var dx = p2.x - p1.x;
    var dy = p2.y - p1.y;
    var len = Math.sqrt(dx * dx + dy * dy);
    var avail = len - 2 * padding;
    
    // Keep text upright
    var angle = Math.atan2(dy, dx);
    if (angle < -Math.PI / 2 || angle > Math.PI / 2) {
      var p = p1;
      p1 = p2;
      p2 = p;
      dx *= -1;
      dy *= -1;
      angle -= Math.PI;
    }
    
    var p = p1;
    var pad = 1 / 2;
    
    ctx.save();
    ctx.textAlign = alignment;
    ctx.translate(p.x + dx * pad, p.y + dy * pad);
    ctx.rotate(angle);
    var fontSize = self.p.defaultLabelSize;
    ctx.font = self.p.fontStyle + fontSize + 'px ' + self.p.font;
    ctx.fillStyle = color;
    ctx.fillText(text, 0, -5);
    ctx.restore();
    };
    

提交回复
热议问题