refactor(edge): add anchor into consideration when drawing loop

This commit is contained in:
yilin.qyl 2019-03-13 15:14:23 +08:00
parent 9bfecd2df6
commit 425d0bef5c
9 changed files with 609 additions and 70 deletions

1
demos/assets/energy.json Normal file
View File

@ -0,0 +1 @@
{"nodes":[{"name":"Agricultural 'waste'"},{"name":"Bio-conversion"},{"name":"Liquid"},{"name":"Losses"},{"name":"Solid"},{"name":"Gas"},{"name":"Biofuel imports"},{"name":"Biomass imports"},{"name":"Coal imports"},{"name":"Coal"},{"name":"Coal reserves"},{"name":"District heating"},{"name":"Industry"},{"name":"Heating and cooling - commercial"},{"name":"Heating and cooling - homes"},{"name":"Electricity grid"},{"name":"Over generation / exports"},{"name":"H2 conversion"},{"name":"Road transport"},{"name":"Agriculture"},{"name":"Rail transport"},{"name":"Lighting & appliances - commercial"},{"name":"Lighting & appliances - homes"},{"name":"Gas imports"},{"name":"Ngas"},{"name":"Gas reserves"},{"name":"Thermal generation"},{"name":"Geothermal"},{"name":"H2"},{"name":"Hydro"},{"name":"International shipping"},{"name":"Domestic aviation"},{"name":"International aviation"},{"name":"National navigation"},{"name":"Marine algae"},{"name":"Nuclear"},{"name":"Oil imports"},{"name":"Oil"},{"name":"Oil reserves"},{"name":"Other waste"},{"name":"Pumped heat"},{"name":"Solar PV"},{"name":"Solar Thermal"},{"name":"Solar"},{"name":"Tidal"},{"name":"UK land based bioenergy"},{"name":"Wave"},{"name":"Wind"}],"links":[{"source":0,"target":1,"value":124.729},{"source":1,"target":2,"value":0.597},{"source":1,"target":3,"value":26.862},{"source":1,"target":4,"value":280.322},{"source":1,"target":5,"value":81.144},{"source":6,"target":2,"value":35},{"source":7,"target":4,"value":35},{"source":8,"target":9,"value":11.606},{"source":10,"target":9,"value":63.965},{"source":9,"target":4,"value":75.571},{"source":11,"target":12,"value":10.639},{"source":11,"target":13,"value":22.505},{"source":11,"target":14,"value":46.184},{"source":15,"target":16,"value":104.453},{"source":15,"target":14,"value":113.726},{"source":15,"target":17,"value":27.14},{"source":15,"target":12,"value":342.165},{"source":15,"target":18,"value":37.797},{"source":15,"target":19,"value":4.412},{"source":15,"target":13,"value":40.858},{"source":15,"target":3,"value":56.691},{"source":15,"target":20,"value":7.863},{"source":15,"target":21,"value":90.008},{"source":15,"target":22,"value":93.494},{"source":23,"target":24,"value":40.719},{"source":25,"target":24,"value":82.233},{"source":5,"target":13,"value":0.129},{"source":5,"target":3,"value":1.401},{"source":5,"target":26,"value":151.891},{"source":5,"target":19,"value":2.096},{"source":5,"target":12,"value":48.58},{"source":27,"target":15,"value":7.013},{"source":17,"target":28,"value":20.897},{"source":17,"target":3,"value":6.242},{"source":28,"target":18,"value":20.897},{"source":29,"target":15,"value":6.995},{"source":2,"target":12,"value":121.066},{"source":2,"target":30,"value":128.69},{"source":2,"target":18,"value":135.835},{"source":2,"target":31,"value":14.458},{"source":2,"target":32,"value":206.267},{"source":2,"target":19,"value":3.64},{"source":2,"target":33,"value":33.218},{"source":2,"target":20,"value":4.413},{"source":34,"target":1,"value":4.375},{"source":24,"target":5,"value":122.952},{"source":35,"target":26,"value":839.978},{"source":36,"target":37,"value":504.287},{"source":38,"target":37,"value":107.703},{"source":37,"target":2,"value":611.99},{"source":39,"target":4,"value":56.587},{"source":39,"target":1,"value":77.81},{"source":40,"target":14,"value":193.026},{"source":40,"target":13,"value":70.672},{"source":41,"target":15,"value":59.901},{"source":42,"target":14,"value":19.263},{"source":43,"target":42,"value":19.263},{"source":43,"target":41,"value":59.901},{"source":4,"target":19,"value":0.882},{"source":4,"target":26,"value":400.12},{"source":4,"target":12,"value":46.477},{"source":26,"target":15,"value":525.531},{"source":26,"target":3,"value":787.129},{"source":26,"target":11,"value":79.329},{"source":44,"target":15,"value":9.452},{"source":45,"target":1,"value":182.01},{"source":46,"target":15,"value":19.013},{"source":47,"target":15,"value":289.366}]}

292
demos/assets/sankey.js Normal file
View File

@ -0,0 +1,292 @@
d3.sankey = function() {
var sankey = {},
nodeWidth = 24,
nodePadding = 8,
size = [1, 1],
nodes = [],
links = [];
sankey.nodeWidth = function(_) {
if (!arguments.length) return nodeWidth;
nodeWidth = +_;
return sankey;
};
sankey.nodePadding = function(_) {
if (!arguments.length) return nodePadding;
nodePadding = +_;
return sankey;
};
sankey.nodes = function(_) {
if (!arguments.length) return nodes;
nodes = _;
return sankey;
};
sankey.links = function(_) {
if (!arguments.length) return links;
links = _;
return sankey;
};
sankey.size = function(_) {
if (!arguments.length) return size;
size = _;
return sankey;
};
sankey.layout = function(iterations) {
computeNodeLinks();
computeNodeValues();
computeNodeBreadths();
computeNodeDepths(iterations);
computeLinkDepths();
return sankey;
};
sankey.relayout = function() {
computeLinkDepths();
return sankey;
};
sankey.link = function() {
var curvature = .5;
function link(d) {
var x0 = d.source.x + d.source.dx,
x1 = d.target.x,
xi = d3.interpolateNumber(x0, x1),
x2 = xi(curvature),
x3 = xi(1 - curvature),
y0 = d.source.y + d.sy + d.dy / 2,
y1 = d.target.y + d.ty + d.dy / 2;
return "M" + x0 + "," + y0
+ "C" + x2 + "," + y0
+ " " + x3 + "," + y1
+ " " + x1 + "," + y1;
}
link.curvature = function(_) {
if (!arguments.length) return curvature;
curvature = +_;
return link;
};
return link;
};
// Populate the sourceLinks and targetLinks for each node.
// Also, if the source and target are not objects, assume they are indices.
function computeNodeLinks() {
nodes.forEach(function(node) {
node.sourceLinks = [];
node.targetLinks = [];
});
links.forEach(function(link) {
var source = link.source,
target = link.target;
if (typeof source === "number") source = link.source = nodes[link.source];
if (typeof target === "number") target = link.target = nodes[link.target];
source.sourceLinks.push(link);
target.targetLinks.push(link);
});
}
// Compute the value (size) of each node by summing the associated links.
function computeNodeValues() {
nodes.forEach(function(node) {
node.value = Math.max(
d3.sum(node.sourceLinks, value),
d3.sum(node.targetLinks, value)
);
});
}
// Iteratively assign the breadth (x-position) for each node.
// Nodes are assigned the maximum breadth of incoming neighbors plus one;
// nodes with no incoming links are assigned breadth zero, while
// nodes with no outgoing links are assigned the maximum breadth.
function computeNodeBreadths() {
var remainingNodes = nodes,
nextNodes,
x = 0;
while (remainingNodes.length) {
nextNodes = [];
remainingNodes.forEach(function(node) {
node.x = x;
node.dx = nodeWidth;
node.sourceLinks.forEach(function(link) {
nextNodes.push(link.target);
});
});
remainingNodes = nextNodes;
++x;
}
//
moveSinksRight(x);
scaleNodeBreadths((width - nodeWidth) / (x - 1));
}
function moveSourcesRight() {
nodes.forEach(function(node) {
if (!node.targetLinks.length) {
node.x = d3.min(node.sourceLinks, function(d) { return d.target.x; }) - 1;
}
});
}
function moveSinksRight(x) {
nodes.forEach(function(node) {
if (!node.sourceLinks.length) {
node.x = x - 1;
}
});
}
function scaleNodeBreadths(kx) {
nodes.forEach(function(node) {
node.x *= kx;
});
}
function computeNodeDepths(iterations) {
var nodesByBreadth = d3.nest()
.key(function(d) { return d.x; })
.sortKeys(d3.ascending)
.entries(nodes)
.map(function(d) { return d.values; });
//
initializeNodeDepth();
resolveCollisions();
for (var alpha = 1; iterations > 0; --iterations) {
relaxRightToLeft(alpha *= .99);
resolveCollisions();
relaxLeftToRight(alpha);
resolveCollisions();
}
function initializeNodeDepth() {
var ky = d3.min(nodesByBreadth, function(nodes) {
return (size[1] - (nodes.length - 1) * nodePadding) / d3.sum(nodes, value);
});
nodesByBreadth.forEach(function(nodes) {
nodes.forEach(function(node, i) {
node.y = i;
node.dy = node.value * ky;
});
});
links.forEach(function(link) {
link.dy = link.value * ky;
});
}
function relaxLeftToRight(alpha) {
nodesByBreadth.forEach(function(nodes, breadth) {
nodes.forEach(function(node) {
if (node.targetLinks.length) {
var y = d3.sum(node.targetLinks, weightedSource) / d3.sum(node.targetLinks, value);
node.y += (y - center(node)) * alpha;
}
});
});
function weightedSource(link) {
return center(link.source) * link.value;
}
}
function relaxRightToLeft(alpha) {
nodesByBreadth.slice().reverse().forEach(function(nodes) {
nodes.forEach(function(node) {
if (node.sourceLinks.length) {
var y = d3.sum(node.sourceLinks, weightedTarget) / d3.sum(node.sourceLinks, value);
node.y += (y - center(node)) * alpha;
}
});
});
function weightedTarget(link) {
return center(link.target) * link.value;
}
}
function resolveCollisions() {
nodesByBreadth.forEach(function(nodes) {
var node,
dy,
y0 = 0,
n = nodes.length,
i;
// Push any overlapping nodes down.
nodes.sort(ascendingDepth);
for (i = 0; i < n; ++i) {
node = nodes[i];
dy = y0 - node.y;
if (dy > 0) node.y += dy;
y0 = node.y + node.dy + nodePadding;
}
// If the bottommost node goes outside the bounds, push it back up.
dy = y0 - nodePadding - size[1];
if (dy > 0) {
y0 = node.y -= dy;
// Push any overlapping nodes back up.
for (i = n - 2; i >= 0; --i) {
node = nodes[i];
dy = node.y + node.dy + nodePadding - y0;
if (dy > 0) node.y -= dy;
y0 = node.y;
}
}
});
}
function ascendingDepth(a, b) {
return a.y - b.y;
}
}
function computeLinkDepths() {
nodes.forEach(function(node) {
node.sourceLinks.sort(ascendingTargetDepth);
node.targetLinks.sort(ascendingSourceDepth);
});
nodes.forEach(function(node) {
var sy = 0, ty = 0;
node.sourceLinks.forEach(function(link) {
link.sy = sy;
sy += link.dy;
});
node.targetLinks.forEach(function(link) {
link.ty = ty;
ty += link.dy;
});
});
function ascendingSourceDepth(a, b) {
return a.source.y - b.source.y;
}
function ascendingTargetDepth(a, b) {
return a.target.y - b.target.y;
}
}
function center(node) {
return node.y + node.dy / 2;
}
function value(link) {
return link.value;
}
return sankey;
};

102
demos/flow-chart.html Normal file
View File

@ -0,0 +1,102 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../src/item/item.js"></script>
</head>
<body>
<div id="mountNode"></div>
<script src="https://gw.alipayobjects.com/os/antv/assets/lib/jquery-3.2.1.min.js"></script>
<script src="../build/g6.js"></script>
<script>
$.getJSON('./assets/data/usa-president.json', data => {
const presidents = {};
const nodeMap = {
birth_place: {},
age: {},
party: {},
sgin: {}
};
const colors = ['#FD8C3D', '#D83F43', '#F7BED6', '#E487C7', '#46A848', '#D83F43', '#3B85BA', '#48335B', '#B7CDE9'];
const nodes = [];
const edges = [];
const V_GAP = 30;
// 数据预处理,整理出各个总统出生地,党派,年龄,星座的统计数据
const params = ['birth_place','age', 'party', 'sgin' ];
let lastParam = 'president';
data.forEach(president => {
presidents[president.president] = president;
params.forEach(param => {
let paramName = president[param];
if (param === 'age') {
paramName = Math.floor(((president.death_year || 2019) - president.birth_year) / 10, 10) * 10 + '';
president.age = paramName;
}
if (!nodeMap[param][paramName]) {
nodeMap[param][paramName] = 1;
} else {
nodeMap[param][paramName] += 1;
}
edges.push({ id: president[lastParam] + ':' + paramName, source: president[lastParam], target: paramName, shape: 'cubic-horizontal' });
lastParam = param;
});
lastParam = 'president';
});
let lastHeight = V_GAP;
Object.keys(nodeMap).forEach((nodeType, i) => {
Object.keys(nodeMap[nodeType]).forEach(node => {
const count = nodeMap[nodeType][node];
nodes.push({
id: node,
x: i * 105 + 195,
y: count * 5 / 2 + lastHeight,
size: [50, height],
style: { fill: colors[Math.round(Math.random() * 9)] },
shape: 'rect',
data: {
count,
type: nodeType
},
label: node,
labelCfg: { position: 'top' }
});
lastHeight += height + V_GAP
});
lastHeight = V_GAP;
});
Object.keys(presidents).forEach(president => {
const data = presidents[president];
nodes.push({
id: data.president,
x: 80,
y: lastHeight + 25,
size: [50, 5],
shape: 'rect',
style: { fill: colors[Math.round(Math.random() * 9)] },
data: data,
label: data.president,
labelCfg: { position: 'top' }
});
lastHeight += 30;
});
const graph = new G6.Graph({
container: 'mountNode',
width: 800,
height: 800,
nodeStyle: {
default: { fill: '#ebebeb' }
},
edgeStyle: {
default: { stroke: 'rgba(0, 0, 0, 0.2)' }
}
});
graph.data({ nodes, edges });
graph.render();
});
</script>
</body>
</html>

View File

@ -3,6 +3,7 @@
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../src/shape/shape.js"></script>
</head>
<body>
<div id="mountNode"></div>

124
demos/sankey-diagram.html Normal file
View File

@ -0,0 +1,124 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="mountNode"></div>
<script src="../build/g6.js"></script>
<script src="./assets/d3-4.13.0.min.js"></script>
<script src="./assets/sankey.js"></script>
<script src="./assets/jquery-3.2.1.min.js"></script>
<script>
const margin = {top: 1, right: 1, bottom: 6, left: 1};
const width = 960 - margin.left - margin.right;
const height = 500 - margin.top - margin.bottom;
const colors = ['#FD8C3D', '#D83F43', '#F7BED6', '#E487C7', '#46A848', '#D83F43', '#3B85BA', '#48335B', '#B7CDE9'];
G6.registerEdge('sankey', {
draw(cfg, group) {
const data = cfg.data;
const shape = group.addShape('path', {
attrs: {
stroke: 'rgba(0, 0, 0, 0.2)',
lineWidth: Math.max(1, data.dy),
path: path(data)
}
});
return shape;
}
}, 'line');
var svg = d3.select("#mountNode").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var sankey = d3.sankey()
.nodeWidth(15)
.nodePadding(10)
.size([width, height]);
var path = sankey.link();
d3.json("./assets/energy.json", function(energy) {
sankey
.nodes(energy.nodes)
.links(energy.links)
.layout(32);
console.log(energy)
const nodes = [];
const edges = [];
energy.nodes.forEach(node => {
nodes.push({
id: node.name,
label: node.name,
style: { fill: colors[Math.round( Math.random() * 9)] },
x: node.x + 7.5,
y: node.y + node.dy / 2 ,
size: [ 15, node.dy ],
shape: 'rect',
labelCfg: { labelPosition: node.x > 480 ? 'right': 'left' }
});
});
energy.links.forEach(edge => {
const source = edge.source;
const target = edge.target;
edges.push({
id: source.name + ':' + target.name,
source: source.name,
target: target.name,
shape: 'sankey',
data: edge
});
});
var link = svg.append("g").selectAll(".link")
.data(energy.links)
.enter().append("path")
.attr("class", "link")
.attr("d", path)
.style("stroke-width", function(d) { return Math.max(1, d.dy); })
.style('stroke', '#ebebeb')
.style('fill', '#ebebeb')
.sort(function(a, b) { return b.dy - a.dy; });
link.append("title")
.text(function(d) { return d.source.name + " → " + d.target.name });
var node = svg.append("g").selectAll(".node")
.data(energy.nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
node.append("rect")
.attr("height", function(d) { return d.dy; })
.attr("width", sankey.nodeWidth())
.style("fill", function(d) { return d.color = '#ccc'; })
.style("stroke", function(d) { return d3.rgb(d.color).darker(2); })
.append("title")
.text(function(d) { return d.name + "\n"; });
node.append("text")
.attr("x", -6)
.attr("y", function(d) { return d.dy / 2; })
.attr("dy", ".35em")
.attr("text-anchor", "end")
.attr("transform", null)
.text(function(d) { return d.name; })
.filter(function(d) { return d.x < width / 2; })
.attr("x", 6 + sankey.nodeWidth())
.attr("text-anchor", "start");
function dragmove(d) {
d3.select(this).attr("transform", "translate(" + d.x + "," + (d.y = Math.max(0, Math.min(height - d.dy, d3.event.y))) + ")");
sankey.relayout();
link.attr("d", path);
}
});
</script>
</body>
</html>

View File

@ -130,27 +130,20 @@ class Edge extends Item {
return this.get(pointName);
}
_getLoopCfgs(cfg) {
const item = this.get('source');
return Util.getLoopCfgs(item, cfg);
}
getShapeCfg(model) {
const self = this;
const linkCenter = this.get('linkCenter'); // 如果连接到中心,忽视锚点、忽视控制点
let cfg = super.getShapeCfg(model);
if (self.get('source') === self.get('target')) {
cfg = this._getLoopCfgs(cfg);
return cfg;
}
const linkCenter = self.get('linkCenter'); // 如果连接到中心,忽视锚点、忽视控制点
const cfg = super.getShapeCfg(model);
if (linkCenter) {
cfg.startPoint = this._getEndCenter('source');
cfg.endPoint = this._getEndCenter('target');
cfg.startPoint = self._getEndCenter('source');
cfg.endPoint = self._getEndCenter('target');
} else {
const controlPoints = cfg.controlPoints || this._getControlPointsByCenter(cfg);
cfg.startPoint = this._getLinkPoint('source', model, controlPoints);
cfg.endPoint = this._getLinkPoint('target', model, controlPoints);
const controlPoints = cfg.controlPoints || self._getControlPointsByCenter(cfg);
cfg.startPoint = self._getLinkPoint('source', model, controlPoints);
cfg.endPoint = self._getLinkPoint('target', model, controlPoints);
}
cfg.sourceNode = self.get('sourceNode');
cfg.targetNode = self.get('targetNode');
return cfg;
}

View File

@ -61,6 +61,7 @@ const singleEdgeDefinition = Util.mix({}, SingleShapeMixin, {
getShapeStyle(cfg) {
const color = cfg.color || Global.defaultEdge.color;
const size = cfg.size || Global.defaultEdge.size;
cfg = this.getPathPoints(cfg);
const startPoint = cfg.startPoint;
const endPoint = cfg.endPoint;
const controlPoints = this.getControlPoints(cfg);
@ -181,6 +182,14 @@ const singleEdgeDefinition = Util.mix({}, SingleShapeMixin, {
getControlPoints(cfg) {
return cfg.controlPoints;
},
/**
* @internal 处理需要重计算点和边的情况
* @param {Object} cfg 边的配置项
* @return {Object} 边的配置项
*/
getPathPoints(cfg) {
return cfg;
},
/**
* 绘制边
* @override
@ -296,3 +305,9 @@ Shape.registerEdge('cubic-horizontal', {
return controlPoints;
}
}, 'cubic');
Shape.registerEdge('loop', {
getPathPoints(cfg) {
return Util.getLoopCfgs(cfg);
}
}, 'cubic');

View File

@ -45,7 +45,8 @@ const GraphicUtil = {
};
},
// 获取某元素的自环边配置
getLoopCfgs(item, cfg) {
getLoopCfgs(cfg) {
const item = cfg.sourceNode || cfg.targetNode;
const containerMatrix = item.get('group')
.getMatrix();
const bbox = item.getKeyShape()
@ -61,50 +62,53 @@ const GraphicUtil = {
const center = [ containerMatrix[ 6 ], containerMatrix[ 7 ] ];
const sinDelta = r * SELF_LINK_SIN;
const cosDelta = r * SELF_LINK_COS;
let startPoint,
endPoint;
switch (position) {
case 'top':
startPoint = [ center[0] - sinDelta, center[1] - cosDelta ];
endPoint = [ center[0] + sinDelta, center[1] - cosDelta ];
break;
case 'top-right':
startPoint = [ center[0] + sinDelta, center[1] - cosDelta ];
endPoint = [ center[0] + cosDelta, center[1] - sinDelta ];
break;
case 'right':
startPoint = [ center[0] + cosDelta, center[1] - sinDelta ];
endPoint = [ center[0] + cosDelta, center[1] + sinDelta ];
break;
case 'bottom-right':
startPoint = [ center[0] + cosDelta, center[1] + sinDelta ];
endPoint = [ center[0] + sinDelta, center[1] + cosDelta ];
break;
case 'bottom':
startPoint = [ center[0] + sinDelta, center[1] + cosDelta ];
endPoint = [ center[0] - sinDelta, center[1] + cosDelta ];
break;
case 'bottom-left':
startPoint = [ center[0] - sinDelta, center[1] + cosDelta ];
endPoint = [ center[0] - cosDelta, center[1] + sinDelta ];
break;
case 'left':
startPoint = [ center[0] - cosDelta, center[1] + sinDelta ];
endPoint = [ center[0] - cosDelta, center[1] - sinDelta ];
break;
case 'top-left':
startPoint = [ center[0] - cosDelta, center[1] - sinDelta ];
endPoint = [ center[0] - sinDelta, center[1] - cosDelta ];
break;
default:
startPoint = [ center[0] - sinDelta, center[1] - cosDelta ];
endPoint = [ center[0] + sinDelta, center[1] - cosDelta ];
}
// 如果逆时针画,交换起点和终点
if (loopCfg.clockwise === false) {
const swap = [ startPoint[0], startPoint[1] ];
startPoint = [ endPoint[0], endPoint[1] ];
endPoint = [ swap[0], swap[1] ];
let startPoint = [ cfg.startPoint.x, cfg.startPoint.y ];
let endPoint = [ cfg.endPoint.x, cfg.endPoint.y ];
// 如果定义了锚点的,直接用锚点坐标,否则,根据自环的 cfg 计算
if (startPoint[0] === endPoint[0] && startPoint[1] === endPoint[1]) {
switch (position) {
case 'top':
startPoint = [ center[0] - sinDelta, center[1] - cosDelta ];
endPoint = [ center[0] + sinDelta, center[1] - cosDelta ];
break;
case 'top-right':
startPoint = [ center[0] + sinDelta, center[1] - cosDelta ];
endPoint = [ center[0] + cosDelta, center[1] - sinDelta ];
break;
case 'right':
startPoint = [ center[0] + cosDelta, center[1] - sinDelta ];
endPoint = [ center[0] + cosDelta, center[1] + sinDelta ];
break;
case 'bottom-right':
startPoint = [ center[0] + cosDelta, center[1] + sinDelta ];
endPoint = [ center[0] + sinDelta, center[1] + cosDelta ];
break;
case 'bottom':
startPoint = [ center[0] + sinDelta, center[1] + cosDelta ];
endPoint = [ center[0] - sinDelta, center[1] + cosDelta ];
break;
case 'bottom-left':
startPoint = [ center[0] - sinDelta, center[1] + cosDelta ];
endPoint = [ center[0] - cosDelta, center[1] + sinDelta ];
break;
case 'left':
startPoint = [ center[0] - cosDelta, center[1] + sinDelta ];
endPoint = [ center[0] - cosDelta, center[1] - sinDelta ];
break;
case 'top-left':
startPoint = [ center[0] - cosDelta, center[1] - sinDelta ];
endPoint = [ center[0] - sinDelta, center[1] - cosDelta ];
break;
default:
startPoint = [ center[0] - sinDelta, center[1] - cosDelta ];
endPoint = [ center[0] + sinDelta, center[1] - cosDelta ];
}
// 如果逆时针画,交换起点和终点
if (loopCfg.clockwise === false) {
const swap = [ startPoint[0], startPoint[1] ];
startPoint = [ endPoint[0], endPoint[1] ];
endPoint = [ swap[0], swap[1] ];
}
}
const startVec = [ startPoint[0] - center[0], startPoint[1] - center[1] ];
const startExtendVec = BaseUtil.vec2.scale([], startVec, scaleRate);

View File

@ -278,56 +278,57 @@ describe('all node link center', () => {
expect(edge.get('keyShape').attr('path')).eqls([[ 'M', 10, 10 ], [ 'L', 100, 100 ]]);
});
it('loop', () => {
const node = graph.addItem('node', { id: 'circleNode', x: 150, y: 150, style: { fill: 'yellow' } });
const edge1 = graph.addItem('edge', { id: 'edge', source: node, target: node,
graph.set('linkCenter', false);
const node = graph.addItem('node', { id: 'circleNode', x: 150, y: 150, style: { fill: 'yellow' }, anchorPoints: [[ 0, 0 ], [ 0, 1 ]] });
const edge1 = graph.addItem('edge', { id: 'edge', source: node, target: node, shape: 'loop',
loopCfg: {
position: 'top',
dist: 60,
clockwise: true
}, style: { endArrow: true }
});
const edge2 = graph.addItem('edge', { id: 'edge1', source: node, target: node,
const edge2 = graph.addItem('edge', { id: 'edge1', source: node, target: node, shape: 'loop',
loopCfg: {
position: 'top-left',
dist: 60,
clockwise: false
}, style: { endArrow: true }
});
const edge3 = graph.addItem('edge', { id: 'edge2', source: node, target: node, shape: 'cubic',
const edge3 = graph.addItem('edge', { id: 'edge2', source: node, target: node, shape: 'loop',
loopCfg: {
position: 'top-right',
dist: 60
}, style: { endArrow: true }
});
const edge4 = graph.addItem('edge', { id: 'edge4', source: node, target: node, shape: 'cubic',
const edge4 = graph.addItem('edge', { id: 'edge4', source: node, target: node, shape: 'loop',
loopCfg: {
position: 'right',
dist: 60,
clockwise: true
}, style: { endArrow: true }
});
graph.addItem('edge', { id: 'edge5', source: node, target: node, shape: 'cubic',
const edgeWithAnchor = graph.addItem('edge', { id: 'edge5', source: node, target: node, shape: 'loop', sourceAnchor: 0, targetAnchor: 1,
loopCfg: {
position: 'bottom-right',
dist: 60,
clockwise: true
}, style: { endArrow: true }
});
graph.addItem('edge', { id: 'edge6', source: node, target: node, shape: 'cubic',
graph.addItem('edge', { id: 'edge6', source: node, target: node, shape: 'loop',
loopCfg: {
position: 'bottom',
dist: 60,
clockwise: true
}, style: { endArrow: true }
});
graph.addItem('edge', { id: 'edge7', source: node, target: node, shape: 'cubic',
graph.addItem('edge', { id: 'edge7', source: node, target: node, shape: 'loop',
loopCfg: {
position: 'bottom-left',
dist: 60,
clockwise: true
}, style: { endArrow: true }
});
graph.addItem('edge', { id: 'edge8', source: node, target: node, shape: 'cubic',
graph.addItem('edge', { id: 'edge8', source: node, target: node, shape: 'loop',
loopCfg: {
position: 'left',
dist: 60,
@ -341,6 +342,12 @@ describe('all node link center', () => {
expect(edge3.getKeyShape().attr('path')[0][1]).to.equal(edgeShape[1][5]);
expect(edge4.getKeyShape().attr('path')[0][1]).to.equal(edge3.getKeyShape().attr('path')[1][5]);
expect(edge4.getKeyShape().attr('path')[0][2]).to.equal(edge3.getKeyShape().attr('path')[1][6]);
const pathWithAnchor = edgeWithAnchor.getKeyShape().attr('path');
expect(pathWithAnchor[0][1]).to.equal(129.5);
expect(pathWithAnchor[0][2]).to.equal(129.5);
expect(pathWithAnchor[1][0]).to.equal('C');
expect(pathWithAnchor[1][5]).to.equal(129.5);
expect(pathWithAnchor[1][6]).to.equal(170.5);
});
it('clear states', () => {
graph.clear();