2

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

在此处输入图像描述

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

这对 RaphaelJS 可行吗?

4

1 回答 1

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 );
}

看看这个小提琴看看结果的一个小例子。

于 2012-08-06T22:58:05.040 回答