如何在sigma.js(canvas渲染器)上的选定节点上添加CSS属性

时间:2016-09-19 16:15:56

标签: javascript canvas sigma.js

我创建了一个函数,当我点击某个节点时,会使所有非相邻节点透明*。现在我想让相同的节点对鼠标事件没有响应,同时保持可见节点的响应。 一种选择是将css属性pointer-events:none分配给透明节点。我可以用sigma做到这一点吗?

*为此,我指定了一个不透明度为0的rgba颜色。因此我必须使用画布渲染器,因为WebGL不支持透明度。

我的代码:

function highlight () {

var s = sigma.instances()[0];
var nodes = s.graph.nodes();
var edges = s.graph.edges();
var maxCollab = d3.max(edges, function(d) { return d.collaborations; });

// We first need to save the original colors of our
// nodes and edges, like this:
nodes.forEach(function(n) {
    n.originalColor = n.color;
  });
edges.forEach(function(e) {
    e.originalColor = e.color;
  });

// When a node is clicked, we check for each node
// if it is a neighbor of the clicked one. If not,
// we set its color as grey, and else, it takes its
// original color.
// We do the same for the edges, and we only keep
// edges that have both extremities colored.
s.bind('clickNode', function(e) {
    var nodeId = e.data.node.id,
        toKeep = s.graph.neighbors(nodeId);
    toKeep[nodeId] = e.data.node;

    nodes.forEach(function(n) {
      if (toKeep[n.id])
        n.color = n.originalColor;
      else
        n.color = 'rgba(0,0,0,0)';
    });

    edges.forEach(function(e) {
      if (toKeep[e.source] && toKeep[e.target]) {
        e.color = e.originalColor;
    }
      else
        e.color = 'rgba(0,0,0,0)';
    });

    // Since the data has been modified, we need to
    // call the refresh method to make the colors
    // update effective.
    s.refresh();
});

// When the stage is clicked, we just color each
// node and edge with its original color.
s.bind('clickStage', function(e) {
    nodes.forEach(function(n) {
      n.color = n.originalColor;
    });

    edges.forEach(function(e) {
      e.color = e.originalColor;
    });
    s.refresh();
});
}

2 个答案:

答案 0 :(得分:1)

你只是想隐藏节点吗?如果是这样,您可以将节点的隐藏属性设置为true。这样他们就不再可见了,西格玛不会为他们发起任何事件。

答案 1 :(得分:0)

您只需在意图对clickNode事件无响应的节点上添加标记即可。

// excerpt from `clickNode` handler
nodes.forEach(function(n) {
  if (toKeep[n.id]) {
    n.color = n.originalColor;
    n.clickable = false; // <-- add this
  } else {
    n.color = 'rgba(0,0,0,0)';
  }
});    

然后只让clickNode处理程序的内容应用于这些节点。

// `clickNode` handler
s.bind('clickNode', function(e) {
    if (e.data.node.clickable) {
        // business as usual
    }
});

请勿忘记在true处理程序中将标记设置为clickStage