日期:2014-05-17  浏览次数:20818 次

用TWaver HTML5定制五彩斑斓的链路
最近有客户提到自定义链路的需求,个人感觉非常有代表意义,现在共享出来给大家参考一下。先来看看需求:
  1. 链路要分成两半,用两种颜色填充。
  2. 填充百分比在不同值域时,用不同颜色。
  3. 显示刻度
  4. 有个开关,可以控制链路变短,变短后,链路只画开始和结束部分(相当于原始链路的缩影),中间不画
  5. 如果有多条链路,链路合并后两端分别显示这些链路中的最高填充百分比

    合并前:

    合并后:

  6. 进入子网后,节点上显示和上层节点的连线信息进入子网前,节点2和子网内节点4之间有链路:

进入子网后,节点4上也显示此链路:

先看看实现的效果,后面我们慢慢解释如何定制链路:

前5个需求可以通过自定义Link和LinkUI实现,需要注意:

  1. 用Link#getBundleLinks获取所有的捆绑链路
  2. 用LinkUI#drawLinePoints画线

完整代码如下:

// 自定义Link构造函数
demo.ScaleLink = function(id, from, to) {
    // 调用基类构造函数
    demo.ScaleLink.superClass.constructor.call(this, id, from, to);
    // 设置链路宽度为10个像素
    this.setStyle('link.width', 10);
    //this.setStyle('link.color', 'rgba(0, 0, 0, 0)');
    // 设置Link类型为平行
    this.setStyle('link.type', 'parallel');
    // 设置链路捆绑的间距为40
    this.setStyle('link.bundle.offset', 40);
    // 设置刻度颜色
    this.setClient('scaleColor', 'black');
    // 设置刻度宽度
    this.setClient('scaleWidth', 1);
    // 设置刻度个数
    this.setClient('scaleNumbers', 4);
    // 设置是否变短
    this.setClient('shortened', false);
    // 设置变短后的长度
    this.setClient('shortenLength', 100);
    // 设置分割线颜色
    this.setClient('splitterColor', 'black');
    // 设置起始填充百分比
    this.setClient('fromFillPercent', 0);
    // 设置结束填充百分比
    this.setClient('toFillPercent', 0);
};
// 设置自定义Link继承twaver.Link
twaver.Util.ext('demo.ScaleLink', twaver.Link, {
    // 重载获取UI类方法,返回自定义UI类
	getCanvasUIClass : function () {
		return demo.ScaleLinkUI;
	},
	// 根据百分比获取填充颜色
	getFillColor: function(percent) {
		if (percent < 0.25) {
			return 'green';
		}
		if (percent < 0.5) {
			return 'yellow';
		}
		if (percent < 0.75) {
			return 'magenta';
		}
		return 'red';
	},
	// 获取起始填充颜色
	getFromFillColor: function () {
		return this.getFillColor(this.getFromFillPercent());
	},
	// 获取结束填充颜色
	getToFillColor: function () {
		return this.getFillColor(this.getToFillPercent());
	},
	// 获取起始百分比
	getFromFillPercent: function () {
	    // 如果是链路捆绑代理,返回所有捆绑链路中填充百分比最大的值
		if (this.isBundleAgent()) {
			var fromAgent = this.getFromAgent(),
				percentKey, maxPercent = 0, percent;
			this.getBundleLinks().forEachSiblingLink(function (link) {
				percentKey = fromAgent === link.getFromAgent() ? 'fromFillPercent' : 'toFillPercent';
				percent = link.getClient(percentKey);
				maxPercent = percent > maxPercent ? percent : maxPercent;
			});
			return maxPercent;
		} else {
			return this.getClient('fromFillPercent');
		}
	},
	// 获取结束百分比
	getToFillPercent: function () {
	    // 如果是链路捆绑代理,返回所有捆绑链路中填充百分比最大的值
		if (this.isBundleAgent()) {
			var toAgent = this.getToAgent(),
				percentKey, maxPercent = 0, percent;
			this.getBundleLinks().forEachSiblingLink(function (link) {
				percentKey = toAgent === link.getToAgent() ? 'toFillPercent' : 'fromFillPercent';
				percent = link.getClient(percentKey);
				maxPerc