前言
在最开始的文章中就提到,使用gojs一个很大的原因就是因为gojs的交互功能比较多。因此为了增加更多的图形交互功能,本文将讲述一下图形节点和连线的选择高亮,包括鼠标移入移出和点击对应的节点。让用户体验更好。
鼠标的移入移出高亮
对于节点的高亮来说,其实很明显的就是改变节点的外观。包括节点的颜色,边框的颜色和宽度。鼠标移入移出的方法名分别为mouseEnter和mouseleave。其示例代码如下
//data
[
{ key: "1", color: "#96D6D9",text:"三国" },
{ key: "1-1", color: "#96D6D9",text:"魏" },
{ key: "1-2", color: "#EFEBCA",text:"蜀" },
{ key: "1-3", color: "#EFEBCA",text:"吴" }
],
[
{ from: "1", to: "1-1" },
{ from: "1", to: "1-2" },
{ from: "1", to: "1-3" },
{ from: "1-1", to: "1-3" },
{ from: "1-2", to: "1-2" }
]
//methods
this.mydiagram.nodeTemplate =
$$(go.Node, "Auto",
{
mouseEnter: mouseEnter,
mouseLeave: mouseLeave
},
$$(go.Shape, "Rectangle",
{ strokeWidth: 2, stroke: null, name: "SHAPE" },
new go.Binding("fill", "color")),
$$(go.TextBlock,
{ margin: 10, font: "bold 18px Verdana", name: "TEXT" },
new go.Binding("text", "text"))
);
mouseEnter(e, obj) {
let shape = obj.findObject("SHAPE");
shape.fill = "#6DAB80";
shape.stroke = "#A6E6A1";
let text = obj.findObject("TEXT");
text.stroke = "white";
};
mouseLeave(e, obj) {
let shape = obj.findObject("SHAPE");
shape.fill = obj.data.color;
shape.stroke = null;
let text = obj.findObject("TEXT");
text.stroke = "black";
};
可以看出在鼠标移入移出的事件中有两个参数,第一个则是绑定的器件的事件对象,第二个则是gojs的原型对象。其中findObject方法可以通过给绘图模板绑定的name属性来获取到对应的绘图模板,然后通过修改对应的绘图模板的属性来达到改变绘图模板的效果。从而达到鼠标移入移出的效果。
鼠标点击实现节点和连线高亮
在有些需求中,不是通过鼠标移入移出来实现对应的交互效果,而是通过点击修改一种状态来实现。从而标记现有的交互行为利于对图形的分析。而在实现的过程中可以通过节点和连线的isHighlight属性来实现。示例如下
this.myDiagram.nodeTemplate =
$$(go.Node, "Auto",
{
click: function(e, node) {
var diagram = node.diagram;
diagram.startTransaction("highlight");
diagram.clearHighlighteds();
node.findLinksOutOf().each(function(l) { l.isHighlighted = true; });
node.findNodesOutOf().each(function(n) { n.isHighlighted = true; });
diagram.commitTransaction("highlight");
}
},
$$(go.Shape, "Rectangle",
{ strokeWidth: 2, stroke: null },
new go.Binding("fill", "color"),
new go.Binding("stroke", "isHighlighted", function(h) { return h ? "red" : "black"; })
.ofObject()),
$$(go.TextBlock,
{ margin: 10, font: "bold 18px Verdana" },
new go.Binding("text", "key"))
);
this.myDiagram.linkTemplate =
$$(go.Link,
{ toShortLength: 4 },
$$(go.Shape,
new go.Binding("stroke", "isHighlighted", function(h) { return h ? "red" : "black"; })
.ofObject(),
new go.Binding("strokeWidth", "isHighlighted", function(h) { return h ? 3 : 1; })
.ofObject()),
$$(go.Shape,
{ toArrow: "Standard", strokeWidth: 0 },
new go.Binding("fill", "isHighlighted", function(h) { return h ? "red" : "black"; })
.ofObject())
);
this.myDiagram.click = function(e) {
e.diagram.commit(function(d) { d.clearHighlighteds(); }, "no highlighteds");
};
可以看出在需要修改的绘图模板的属性通过isHighlighted,然后通过修改对应的值来触发后面的回调函数,然后达到修改高亮的属性样式的效果,然后在节点的点击事件来通过点击的节点来前面的查询方法来获取到需要变高亮的节点或者连线,然后通过each方法给对应的节点和连线的isHighlighted属性设置为true就可以了。当然为了解除点击的样式修改,可以给图表绑定对应的点击事件来清除所有节点连线的高亮属性。
总结
为了增加可视化图形的交互,本文介绍了节点的鼠标移入移出和点击事件的来修改操作的节点或者关联的节点和连线的样式修改。以达到做对应动作的时候,显示出一个高亮的效果。