RaphaelJS中的标记节点用于图论理论图

时间:2012-08-06 04:00:36

标签: javascript graph raphael graph-theory

我正在尝试RaphaelJS绘制图论理论风格图。例如:

enter image description here

虽然在RaphaelJS中创建圆/节点很容易,但我还没有想出如何将每个节点与标签相关联(并在每个节点中都有标签)。

RaphaelJS是否可行?

1 个答案:

答案 0 :(得分:5)

我会编写一些代码来使用默认样式管理一系列此类节点,允许根据需要进行覆盖。

// "Constructor" -- accepts a Raphael paper to use as background object and default values for node radius, node style, and label style.
function NodeManager( paper, node_radius, node_style, label_style )
{
    this.paper = paper;
    this.nodes = {};
    this.node_radius = node_radius || 24;
    this.node_style = node_style || { fill: 'white', stroke: 'black', 'stroke-width': 3 };
    this.label_style = label_style || { fill: 'black', stroke: 'none', 'font-family': 'Arial,Helvetica,sans-serif', 'font-size': 32, 'font-weight': 600 };
}

// Add a node to the paper.  
// Code is an arbitrary or symbolic name; 
// x and y are the coordinates the node is centered on; 
// label is the node's textual content (no clipping is performed, so be careful!); 
// node_radius, node_style, and label_style are optional, and can be used to override the appearance of this node.
NodeManager.prototype.addNode = function addNode( code, x, y, label, node_radius, node_style, label_style )
{
    var node = this.paper.circle( x, y, node_radius || this.node_radius ).attr( node_style || this.node_style );
    var label_object = this.paper.text( x, y, label ).attr( label_style || this.label_style );
    this.nodes[code] =
        {
            x: x,
            y: y,
            r: node_radius || this.node_radius,
            node: node,
            label: label_object
        };
}

// Connect the nodes corresponding to the two given codes.  connection_style can be used to override the appearance of the connective link, but the default node_style will be used if it isn't specified.
NodeManager.prototype.connectNodes = function connectNodes( code1, code2, connection_style )
{  
    var angle = Math.atan2(this.nodes[code2].y - this.nodes[code1].y, this.nodes[code2].x - this.nodes[code1].x );      //  this will be the angle from point to point
    var inverse_angle = angle + Math.PI;

    ox1 = this.nodes[code1].x + Math.cos( angle ) * this.nodes[code1].r;
    oy1 = this.nodes[code1].y + Math.sin( angle ) * this.nodes[code1].r;

    ox2 = this.nodes[code2].x + Math.cos( inverse_angle ) * this.nodes[code2].r;
    oy2 = this.nodes[code2].y + Math.sin( inverse_angle ) * this.nodes[code2].r;

    var pathstr = "M" + ox1 + "," + oy1 + " L" + ox2 + "," + oy2;

    var path = this.paper.path( pathstr ).attr( connection_style || this.node_style );
}

查看this fiddle以查看结果的一些示例。