fix: delete pixelRatio for demos, docs, examples, and tests. add: changelog. add: performance demos.

This commit is contained in:
Yanyan-Wang 2020-01-13 20:36:19 +08:00 committed by Yanyan Wang
parent b4bc164116
commit f09bcebb17
263 changed files with 9889 additions and 4814 deletions

View File

@ -1,7 +1,14 @@
# ChangeLog
#### 3.3
- Graph API
- delete removeEvent function, use off;
- refactor: delete removeEvent function, use off;
- refactor: parameters of Shape animate changed, shape.animate(toAttrs, animateCfg) or shape.animate(onFrame, animateCfg);
- feat: descriptionCfg for modelRect to define the style of description by user;
- feat: update a node from without some shapes to with them, such as linkPoints, label, logo icon and state icon for modelRect;
- feat: the callback paramter of event nodeselectchange is changed to { target, selectedItems, ... };
- feat: support stateStyles in node and edge data;
- feat: calculate pixelRatio by G automatically, user do not need to assign it to graph instance;
- chore: G 4.0
#### 3.1.5
* feat: supports g6 types file

Binary file not shown.

Before

Width:  |  Height:  |  Size: 476 B

After

Width:  |  Height:  |  Size: 442 B

View File

@ -26,21 +26,21 @@
}, 'circle');
G6.registerEdge('loop-growth', {
afterDraw(cfg, group) {
const shape = group.get('children')[0];
const length = shape.getTotalLength();
shape.animate({
onFrame(ratio) {
const startLen = ratio * length;
// 计算线的lineDash
const cfg = {
lineDash: [startLen, length - startLen]
};
return cfg;
},
repeat: true
}, 2000);
}
afterDraw(cfg, group) {
const shape = group.get('children')[0];
const length = shape.getTotalLength();
shape.animate(ratio => {
const startLen = ratio * length;
// 计算线的lineDash
const cfg = {
lineDash: [startLen, length - startLen]
};
return cfg;
}, {
repeat: true,
duration: 2000
});
}
}, 'loop');
const data = {

View File

@ -79,18 +79,16 @@
r: 3
}
});
circle.animate({
onFrame(ratio) {
const tmpPoint = shape.getPoint(ratio);
return {
x: tmpPoint.x,
y: tmpPoint.y
};
},
repeat: true
},
3000);
circle.animate(ratio => {
const tmpPoint = shape.getPoint(ratio);
return {
x: tmpPoint.x,
y: tmpPoint.y
};
}, {
repeat: true,
duration: 3000
});
}
},
'cubic');
@ -109,17 +107,16 @@
totalArray = totalArray.concat(lineDash);
}
let index = 0;
shape.animate({
onFrame(ratio) {
const cfg = {
lineDash: dashArray[index].concat(totalArray)
};
index = (index + 1) % interval;
return cfg;
},
repeat: true
},
3000);
shape.animate(ratio => {
const cfg = {
lineDash: dashArray[index].concat(totalArray)
};
index = (index + 1) % interval;
return cfg;
}, {
repeat: true,
duration: 3000
});
}
},
'cubic');
@ -128,18 +125,17 @@
afterDraw(cfg, group) {
const shape = group.get('children')[0];
const length = shape.getTotalLength(); // G 增加了 totalLength 的接口
shape.animate({
onFrame(ratio) {
const startLen = ratio * length;
const cfg = {
lineDash: [startLen, length - startLen]
};
shape.animate(ratio => {
const startLen = ratio * length;
const cfg = {
lineDash: [startLen, length - startLen]
};
return cfg;
},
repeat: true
},
2000);
return cfg;
}, {
repeat: true,
duration: 2000
});
}
},
'cubic');

View File

@ -114,17 +114,16 @@
totalArray = totalArray.concat(lineDash);
}
let index = 0;
shape.animate({
onFrame(ratio) {
const cfg = {
lineDash: dashArray[index].concat(totalArray)
};
index = (index + 1) % interval;
return cfg;
},
repeat: true
},
3000);
shape.animate(ratio => {
const cfg = {
lineDash: dashArray[index].concat(totalArray)
};
index = (index + 1) % interval;
return cfg;
}, {
repeat: true,
duration: 3000
});
} else {
shape.stopAnimate();
shape.attr('lineDash', null);

View File

@ -18,16 +18,16 @@
const cfg = item.get('model');
if (name === 'running') {
if (value) {
shape.animate({
shape.animate(ratio => {
const diff = ratio <= 0.5 ? ratio * 10 : (1 - ratio) * 10;
return {
r: cfg.size / 2 + diff
};
}, {
repeat: true,
onFrame: function onFrame(ratio) {
const diff = ratio <= 0.5 ? ratio * 10 : (1 - ratio) * 10;
return {
r: cfg.size / 2 + diff
};
}
},
1000, 'easeCubic');
duration: 1000,
easing: 'easeCubic'
});
} else {
shape.stopAnimate();
shape.attr('lineDash', null);

Binary file not shown.

Before

Width:  |  Height:  |  Size: 997 KiB

After

Width:  |  Height:  |  Size: 767 KiB

File diff suppressed because one or more lines are too long

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 3.9 KiB

View File

@ -68,22 +68,31 @@
const delayBase = Math.random() * 2000;
back1.animate({ // 逐渐放大,并消失
r: r + 10,
opacity: 0.0,
repeat: true // 循环
},
3000, 'easeCubic', null, delayBase) // 无延迟
opacity: 0.0
}, {
repeat: true, // 循环
duration: 3000,
easing: 'easeCubic',
delay: delayBase // 无延迟
});
back2.animate({ // 逐渐放大,并消失
r: r + 10,
opacity: 0.0,
repeat: true // 循环
},
3000, 'easeCubic', null, delayBase + 1000) // 1 秒延迟
opacity: 0.0
}, {
repeat: true, // 循环
duration: 3000,
easing: 'easeCubic',
delay: delayBase + 1000 // 1 秒延迟
});
back3.animate({ // 逐渐放大,并消失
r: r + 10,
opacity: 0.0,
repeat: true // 循环
},
3000, 'easeCubic', null, delayBase + 2000) // 2 秒延迟
opacity: 0.0
}, {
repeat: true, // 循环
duration: 3000,
easing: 'easeCubic',
delay: delayBase + 2000 // 2 秒延迟
});
}
},
'circle');
@ -109,21 +118,22 @@
shadowBlur: 30,
}
});
circle.animate({
onFrame(ratio) {
ratio += i / circleCount;
if (ratio > 1) {
ratio %= 1;
}
const tmpPoint = shape.getPoint(ratio);
return {
x: tmpPoint.x,
y: tmpPoint.y
};
},
repeat: true
},
10 * length, 'easeCubic', null, delay);
circle.animate(ratio => {
ratio += i / circleCount;
if (ratio > 1) {
ratio %= 1;
}
const tmpPoint = shape.getPoint(ratio);
return {
x: tmpPoint.x,
y: tmpPoint.y
};
}, {
repeat: true,
duration: 10 * length,
easing: 'easeCubic',
delay
});
}
}
},

View File

@ -61,15 +61,19 @@
// 加上交互动画
fan.on('mouseenter', function(evt) {
fan.animate({
re: re + 8,
repeat: false
}, 300);
re: re + 8
}, {
repeat: false,
duration: 300
});
});
fan.on('mouseleave', function(evt) {
fan.animate({
re:re,
repeat: false
}, 300);
re:re
}, {
repeat: false,
duration: 300
});
});
// 设置class

View File

@ -73,15 +73,19 @@
// 加上交互动画
fan.on('mouseenter', function(evt) {
fan.animate({
re: re + 8,
repeat: false
}, 300);
re: re + 8
}, {
repeat: false,
duration: 300
});
});
fan.on('mouseleave', function(evt) {
fan.animate({
re:re,
repeat: false
}, 300);
re: re
}, {
repeat: false,
duration: 300
});
});
// 设置class
@ -193,15 +197,19 @@
// 加上交互动画
littleCircle.on('mouseenter', function(evt) {
littleCircle.animate({
r: 5,
repeat: false
}, 200);
r: 5
}, {
repeat: false,
duration: 200
});
});
littleCircle.on('mouseleave', function(evt) {
littleCircle.animate({
r: 2,
repeat: false
}, 200);
r: 2
}, {
repeat: false,
duration: 200
});
});
// 设置class
littleCircle.set("className", 'littleCircle');

View File

@ -94,15 +94,19 @@
// 加上交互动画
littleCircle.on('mouseenter', function(evt) {
littleCircle.animate({
r: 5,
repeat: false
}, 200);
r: 5
}, {
repeat: false,
duration: 200
});
});
littleCircle.on('mouseleave', function(evt) {
littleCircle.animate({
r: 2,
repeat: false
}, 200);
r: 2
}, {
repeat: false,
duration: 200
});
});
// 设置class
littleCircle.set("className", 'littleCircle');

View File

@ -14,7 +14,6 @@
container: 'mountNode',
width: 500,
height: 500,
pixelRatio: 2,
renderer: 'svg',
modes: {
default: ['collapse-expand', 'drag-canvas']

View File

@ -126,7 +126,6 @@
container: 'mountNode',
width: 500,
height: 500,
pixelRatio: 2,
renderer: 'svg',
modes: {
default: ['drag-canvas']

View File

@ -0,0 +1,153 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>默认的图片节点</title>
</head>
<body>
<div id="mountNode"></div>
<div id="mountNode1"></div>
<script src="../build/g6.js"></script>
<script>
const data = {
nodes: [
{
id: 'node',
x: 200,
y: 200,
shape: 'rect'
}
],
edges: [
{
source: 'node',
target: 'node',
shape: 'loop',
loopCfg: {
position: 'top',
}
},
{
source: 'node',
target: 'node',
shape: 'loop',
loopCfg: {
position: 'top-left',
}
},
{
source: 'node',
target: 'node',
shape: 'loop',
loopCfg: {
position: 'top-right',
}
},
{
source: 'node',
target: 'node',
shape: 'loop',
loopCfg: {
position: 'left',
}
},
{
source: 'node',
target: 'node',
shape: 'loop',
loopCfg: {
position: 'right',
}
},
{
source: 'node',
target: 'node',
shape: 'loop',
loopCfg: {
position: 'bottom-left',
}
},
{
source: 'node',
target: 'node',
shape: 'loop',
loopCfg: {
position: 'bottom-right',
}
},
{
source: 'node',
target: 'node',
shape: 'loop',
loopCfg: {
position: 'bottom',
}
}
]
}
const graph = new G6.Graph({
container: 'mountNode',
width: 800,
height: 600,
defaultNode: {
shape: 'rect',
size: [60, 30],
color: 'green',
},
modes: {
default: ['drag-canvas', 'drag-node', {
type: 'brush-select',
trigger: 'ctrl'
}]
}
})
graph.data(data)
graph.render()
// graph.on('node:click', evt => {
// const { item } = evt
// graph.setItemState(item, 'select', true)
// graph.updateItem(item, {
// size: [ 260, 130],
// style: {
// opacity: 0.6
// },
// preRect: {
// fill: 'blue'
// },
// linkPoints: {
// fill: '#fff',
// size: 5
// },
// stateIcon: {
// img: 'https://gw.alipayobjects.com/zos/basement_prod/c781088a-c635-452a-940c-0173663456d4.svg'
// }
// })
// })
// graph.on('node:mouseenter', evt => {
// const { item } = evt
// graph.setItemState(item, 'hover', true)
// })
// graph.on('node:mouseleave', evt => {
// const { item } = evt
// graph.setItemState(item, 'hover', false)
// })
// graph.addItem('group', {
// nodes: ['image', 'triangle'],
// type: 'rect',
// zIndex: 0,
// title: {
// text: '名称'
// }
// })
</script>
</body>
</html>

View File

@ -12,41 +12,232 @@
<script src="../build/g6.js"></script>
<script>
G6.registerNode('selfCircle', {
drawShape(cfg, group) {
const style = this.getShapeStyle(cfg)
debugger
console.log(style)
const keyShape = group.addShape('circle', {
attrs: style
})
return keyShape
},
afterDraw(cfg, group) {
const shape = group.addShape('rect', {
attrs: {
x: 0,
y: 0,
width: 20,
height: 30,
fill: 'blue'
}
})
return shape
}
}, 'circle')
const edgeTypeColorMap = {
type1: ['#531dab', '#391085', '#391085'],
type2: ['#d9d9d9', '#bfbfbf', '#8c8c8c'],
type3: ['#d3adf7', '#b37feb', '#9254de']
}
let nodes = []
for(let i = 0; i < 500; i++) {
nodes.push({
id: `node-${i}`,
label: `label-${i}`,
x: Math.random() * 650,
y: Math.random() * 550
})
const generateArrow = (lineWidth) => {
let width = (lineWidth * 4) / 3;
return [
['M', lineWidth / 2, 0],
['L', -width * 1.5, -width * 1.5],
['L', -width * 1.5, width * 1.5],
// ['A', radius, radius, 0, 0, 1, -width / 2, halfHeight],
['Z']
];
}
const defaultConf = {
style: {
lineAppendWidth: 5,
lineDash: [0, 0],
lineDashOffset: 0,
endArrow: true,
opacity: 1,
labelCfg: {
style: {
fillOpacity: 1
}
}
},
/**
* 绘制边
* @override
* @param {Object} cfg 边的配置项
* @param {G.Group} group 边的容器
* @return {G.Shape} 图形
*/
drawShape(cfg, group) {
const item = group.get('item')
const shapeStyle = this.getShapeStyle(cfg, item);
const shape = group.addShape('path', {
className: 'edge-path',
attrs: shapeStyle
});
return shape;
},
drawLabel(cfg, group) {
const labelCfg = cfg.labelCfg || {}
const labelStyle = this.getLabelStyle(cfg, labelCfg, group)
const text = group.addShape('text', {
attrs: {
...labelStyle,
text: cfg.label,
fontSize: 12,
fill: '#404040',
cursor: 'pointer'
},
className: 'edge-label'
})
return text
},
/**
* 获取图形的配置项
* @internal 仅在定义这一类节点使用,用户创建和更新节点
* @param {Object} cfg 节点的配置项
* @return {Object} 图形的配置项
*/
getShapeStyle(cfg, item) {
const { startPoint, endPoint } = cfg
const type = item.get('type')
const defaultStyle = this.getStateStyle('default', true, item)
if(type === 'node') {
return Object.assign({}, cfg.style, defaultStyle);
}
const controlPoints = this.getControlPoints(cfg);
let points = [ startPoint ]; // 添加起始点
// 添加控制点
if (controlPoints) {
points = points.concat(controlPoints);
}
// 添加结束点
points.push(endPoint);
const path = this.getPath(points);
const style = Object.assign({}, { path }, cfg.style, defaultStyle);
return style;
},
getControlPoints(cfg) {
let controlPoints = cfg.controlPoints; // 指定controlPoints
if (!controlPoints || !controlPoints.length) {
const { startPoint, endPoint } = cfg;
const innerPoint = G6.Util.getControlPoint(startPoint, endPoint, 0.5, cfg.edgeOffset || 30);
controlPoints = [ innerPoint ];
}
return controlPoints;
},
/**
* 获取三次贝塞尔曲线的path
*
* @param {array} points 起始点和两个控制点
* @returns
*/
getPath(points) {
const path = [];
path.push([ 'M', points[0].x, points[0].y ]);
path.push([ 'Q', points[1].x, points[1].y, points[2].x, points[2].y ]);
return path;
},
/**
* 根据不同状态,获取不同状态下的样式值
* @param {string} name
* @param {string} value
* @param {Item} item
*/
getStateStyle(name, value, item) {
const model = item.getModel()
const { style = {} } = model
const defaultStyle = Object.assign({}, this.style)
// 更新颜色
return {
...defaultStyle,
lineWidth: 1,
stroke: edgeTypeColorMap[model.edgeType] && edgeTypeColorMap[model.edgeType][0],
...style
}
},
/**
* 拖动时更新path及边的label
*
* @param {object} cfg 边的model
* @param {Edge} item 边的实例
*/
update(cfg, item) {
const { data, style,
startPoint, endPoint, labelCfg = {} } = cfg
const group = item.getContainer()
const model = data || cfg
let arrowWidth = 2
const defaultStyle = Object.assign({}, this.style, {
lineWidth: 1,
stroke: edgeTypeColorMap[model.edgeType] && edgeTypeColorMap[model.edgeType][0],
endArrow: {
path: generateArrow(arrowWidth),
}
}, style)
const { opacity, onlyHideText } = defaultStyle
// 更新 path
const keyShape = item.getKeyShape();
const controlPoints = this.getControlPoints(cfg);
keyShape.attr({
path: [
['M', startPoint.x, startPoint.y],
['Q', controlPoints[0].x, controlPoints[0].y, endPoint.x, endPoint.y]
],
...defaultStyle
});
const labelStyle = this.getLabelStyle(cfg, labelCfg, group);
const text = group.findByClassName('edge-label');
const attrs = _.omit({
...labelStyle,
fillOpacity: onlyHideText ? 0 : opacity === 0 ? opacity : 1,
fill: '#404040'
}, 'stroke')
if(text) {
text.resetMatrix();
text.attr(attrs);
}
}
};
G6.registerEdge('quadratic-label-edge', defaultConf, 'quadratic');
// let nodes = []
// for(let i = 0; i < 500; i++) {
// nodes.push({
// id: `node-${i}`,
// label: `label-${i}`,
// x: Math.random() * 650,
// y: Math.random() * 550
// })
// }
const data = {
nodes
nodes: [
{
id: 'node1',
label: 'node1'
},
{
id: 'node2',
label: 'node2'
}
],
edges: [
{
source: 'node1',
target: 'node2',
edgeType: 'type1'
},
{
source: 'node2',
target: 'node1',
edgeType: 'type2'
},
{
source: 'node1',
target: 'node2',
edgeType: 'type3',
edgeOffset: -10
}
]
}
const graph = new G6.Graph({
@ -77,6 +268,9 @@ let nodes = []
fill: '#fff'
}
},
defaultEdge: {
shape: 'quadratic-label-edge'
},
nodeStateStyles: {
hover: {
fill: '#d3adf7'

View File

@ -394,6 +394,9 @@
container: 'mountNode',
width: 1000,
height: 800,
// fitView: true,
// fitViewPadding: 40,
animate: true,
layout: {
type: 'circular',
center: [500, 400],
@ -413,6 +416,9 @@
d: 4
}
}
},
modes: {
default: ['drag-canvas', 'zoom-canvas']
}
});
graph.data(data);

View File

@ -269,7 +269,6 @@
container: 'mountNode',
width: 500,
height: 500,
pixelRatio: 2,
modes: {
default: ['drag-canvas', 'zoom-canvas', 'click-select', {
type: 'tooltip',

View File

@ -243,7 +243,6 @@
// nodesep: 500,
// ranksep: 200
},
pixelRatio: 2,
defaultNode: {
shape: 'sql'
},

View File

@ -67,7 +67,6 @@
container: 'mountNode',
width: 1000,
height: 800,
pixelRatio: 2,
//renderer: 'svg',
animate: false,
modes: {

View File

@ -0,0 +1,437 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MDS Layout</title>
</head>
<body>
<div id="mountNode"></div>
<script src="../build/g6.js"></script>
<script>
const data = {
"nodes": [
{
"id": "0",
"label": "0",
x: 10,
y: 10,
color: 'red'
},
{
"id": "1",
"label": "1",
x: 10,
y: 20,
color: 'red'
},
{
"id": "2",
"label": "2",
x: 10,
y: 30,
color: 'red'
},
{
"id": "3",
"label": "3",
x: 10,
y: 40,
color: 'red'
},
{
"id": "4",
"label": "4",
x: 10,
y: 50,
color: 'red'
},
{
"id": "5",
"label": "5"
},
{
"id": "6",
"label": "6"
},
{
"id": "7",
"label": "7"
},
{
"id": "8",
"label": "8"
},
{
"id": "9",
"label": "9"
},
{
"id": "10",
"label": "10"
},
{
"id": "11",
"label": "11"
},
{
"id": "12",
"label": "12"
},
{
"id": "13",
"label": "13"
},
{
"id": "14",
"label": "14"
},
{
"id": "15",
"label": "15"
},
{
"id": "16",
"label": "16"
},
{
"id": "17",
"label": "17"
},
{
"id": "18",
"label": "18"
},
{
"id": "19",
"label": "19"
},
{
"id": "20",
"label": "20"
},
{
"id": "21",
"label": "21"
},
{
"id": "22",
"label": "22"
},
{
"id": "23",
"label": "23"
},
{
"id": "24",
"label": "24"
},
{
"id": "25",
"label": "25"
},
{
"id": "26",
"label": "26"
},
{
"id": "27",
"label": "27"
},
{
"id": "28",
"label": "28"
},
{
"id": "29",
"label": "29"
},
{
"id": "30",
"label": "30"
},
{
"id": "31",
"label": "31"
},
{
"id": "32",
"label": "32"
},
{
"id": "33",
"label": "33"
}],
"edges": [{
"source": "0",
"target": "1"
},
{
"source": "0",
"target": "2"
},
{
"source": "0",
"target": "3"
},
{
"source": "0",
"target": "4"
},
{
"source": "0",
"target": "5"
},
{
"source": "0",
"target": "7"
},
{
"source": "0",
"target": "8"
},
{
"source": "0",
"target": "9"
},
{
"source": "0",
"target": "10"
},
{
"source": "0",
"target": "11"
},
{
"source": "0",
"target": "13"
},
{
"source": "0",
"target": "14"
},
{
"source": "0",
"target": "15"
},
{
"source": "0",
"target": "16"
},
{
"source": "2",
"target": "3"
},
{
"source": "4",
"target": "5"
},
{
"source": "4",
"target": "6"
},
{
"source": "5",
"target": "6"
},
{
"source": "7",
"target": "13"
},
{
"source": "8",
"target": "14"
},
{
"source": "9",
"target": "10"
},
{
"source": "10",
"target": "22"
},
{
"source": "10",
"target": "14"
},
{
"source": "10",
"target": "12"
},
{
"source": "10",
"target": "24"
},
{
"source": "10",
"target": "21"
},
{
"source": "10",
"target": "20"
},
{
"source": "11",
"target": "24"
},
{
"source": "11",
"target": "22"
},
{
"source": "11",
"target": "14"
},
{
"source": "12",
"target": "13"
},
{
"source": "16",
"target": "17"
},
{
"source": "16",
"target": "18"
},
{
"source": "16",
"target": "21"
},
{
"source": "16",
"target": "22"
},
{
"source": "17",
"target": "18"
},
{
"source": "17",
"target": "20"
},
{
"source": "18",
"target": "19"
},
{
"source": "19",
"target": "20"
},
{
"source": "19",
"target": "33"
},
{
"source": "19",
"target": "22"
},
{
"source": "19",
"target": "23"
},
{
"source": "20",
"target": "21"
},
{
"source": "21",
"target": "22"
},
{
"source": "22",
"target": "24"
},
{
"source": "22",
"target": "25"
},
{
"source": "22",
"target": "26"
},
{
"source": "22",
"target": "23"
},
{
"source": "22",
"target": "28"
},
{
"source": "22",
"target": "30"
},
{
"source": "22",
"target": "31"
},
{
"source": "22",
"target": "32"
},
{
"source": "22",
"target": "33"
},
{
"source": "23",
"target": "28"
},
{
"source": "23",
"target": "27"
},
{
"source": "23",
"target": "29"
},
{
"source": "23",
"target": "30"
},
{
"source": "23",
"target": "31"
},
{
"source": "23",
"target": "33"
},
{
"source": "32",
"target": "33"
}]
};
const graph = new G6.Graph({
container: 'mountNode',
width: 1000,
height: 600,
// fitView: true,
layout: {
type: 'force'
},
defaultNode: {
size: [20, 20],
color: 'steelblue'
},
defaultEdge: {
size: 1,
color: '#e2e2e2'
}
});
graph.data({
nodes: data.nodes,
edges: data.edges.map((edge, i) => {
edge.id = 'edge' + i;
return Object.assign({},
edge);
})
});
graph.render();
</script>
</body>
</html>

View File

@ -0,0 +1,123 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Circular Layout</title>
</head>
<body>
<div id="mountNode"></div>
<script src="../build/g6.js"></script>
<script src="./assets/d3-4.13.0.min.js"></script>
<script>
const data = {
"nodes": [{
"id": "0",
"label": "0",
"x": 100,
"y": 30
},
{
"id": "1",
"label": "1",
"x": 150,
"y": 80
},
{
"id": "2",
"label": "2",
"x": 50,
"y": 80
}],
"edges": [{
"source": "0",
"target": "1"
},
{
"source": "0",
"target": "2"
}, {
"source": "2",
"target": "1"
}]
};
const data2 = {
"nodes": [{
"id": "0",
"label": "0",
"x": 200,
"y": 130
},
{
"id": "n1",
"label": "n1",
"x": 250,
"y": 180
},
{
"id": "n2",
"label": "n2",
"x": 150,
"y": 180
},
{
"id": "n3",
"label": "n3",
"x": 200,
"y": 210
}],
"edges": [{
"source": "0",
"target": "n1"
},
{
"source": "0",
"target": "n2"
},
{
"source": "n2",
"target": "n1"
},
{
"source": "n2",
"target": "n3"
}]
};
const graph = new G6.Graph({
container: 'mountNode',
width: 1000,
height: 800,
animate: true,
// layout: {
// type: 'circular',
// center: [500, 300],
// radius: 200,
// ordering: null
// },
defaultNode: {
size: [20, 20],
color: 'steelblue'
},
defaultEdge: {
size: 1,
color: '#e2e2e2',
style: {
endArrow: {
path: 'M 4,0 L -4,-4 L -4,4 Z',
d: 4
}
}
}
});
graph.data(data);
graph.render();
setTimeout(function () {
graph.changeData(data2);
}, 3000);
</script>
</body>
</html>

View File

@ -0,0 +1,496 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Radial Layout</title>
</head>
<body>
<div id="description">click canvas to add data</div>
<div id="mountNode"></div>
<script src="../build/g6.js"></script>
<script src="./assets/d3-4.13.0.min.js"></script>
<script src="../build/radial.js"></script>
<script>
const usingData = {
nodes: [{
id: "0",
label: "0"
},
{
id: "1",
label: "1"
},
{
id: "2",
label: "2"
},
{
id: "3",
label: "3"
},
{
id: "4",
label: "4"
},
{
id: "5",
label: "5"
},
{
id: "6",
label: "6"
},
{
id: "7",
label: "7"
},
{
id: "8",
label: "8"
},
{
id: "9",
label: "9"
},
{
id: "10",
label: "10"
},
{
id: "11",
label: "11"
},
{
id: "12",
label: "12"
},
{
id: "13",
label: "13"
},
{
id: "14",
label: "14"
},
{
id: "15",
label: "15"
},
{
id: "16",
label: "16"
},
{
id: "17",
label: "17"
},
{
id: "18",
label: "18"
},
{
id: "19",
label: "19"
},
{
id: "20",
label: "20"
},
{
id: "21",
label: "21"
},
{
id: "22",
label: "22"
},
{
id: "23",
label: "23"
},
{
id: "24",
label: "24"
},
{
id: "25",
label: "25"
},
{
id: "26",
label: "26"
},
{
id: "27",
label: "27"
},
{
id: "28",
label: "28"
},
{
id: "29",
label: "29"
},
{
id: "30",
label: "30"
},
{
id: "31",
label: "31"
},
{
id: "32",
label: "32"
},
{
id: "33",
label: "33"
}],
edges: [{
source: "0",
target: "1"
},
{
source: "0",
target: "2"
},
{
source: "0",
target: "3"
},
{
source: "0",
target: "4"
},
{
source: "0",
target: "5"
},
{
source: "0",
target: "7"
},
{
source: "0",
target: "8"
},
{
source: "0",
target: "9"
},
{
source: "0",
target: "10"
},
{
source: "0",
target: "11"
},
{
source: "0",
target: "13"
},
{
source: "0",
target: "14"
},
{
source: "0",
target: "15"
},
{
source: "0",
target: "16"
},
{
source: "2",
target: "3"
},
{
source: "4",
target: "5"
},
{
source: "4",
target: "6"
},
{
source: "5",
target: "6"
},
{
source: "7",
target: "13"
},
{
source: "8",
target: "14"
},
{
source: "9",
target: "10"
},
{
source: "10",
target: "22"
},
{
source: "10",
target: "14"
},
{
source: "10",
target: "12"
},
{
source: "10",
target: "24"
},
{
source: "10",
target: "21"
},
{
source: "10",
target: "20"
},
{
source: "11",
target: "24"
},
{
source: "11",
target: "22"
},
{
source: "11",
target: "14"
},
{
source: "12",
target: "13"
},
{
source: "16",
target: "17"
},
{
source: "16",
target: "18"
},
{
source: "16",
target: "21"
},
{
source: "16",
target: "22"
},
{
source: "17",
target: "18"
},
{
source: "17",
target: "20"
},
{
source: "18",
target: "19"
},
{
source: "19",
target: "20"
},
{
source: "19",
target: "33"
},
{
source: "19",
target: "22"
},
{
source: "19",
target: "23"
},
{
source: "20",
target: "21"
},
{
source: "21",
target: "22"
},
{
source: "22",
target: "24"
},
{
source: "22",
target: "25"
},
{
source: "22",
target: "26"
},
{
source: "22",
target: "23"
},
{
source: "22",
target: "28"
},
{
source: "22",
target: "30"
},
{
source: "22",
target: "31"
},
{
source: "22",
target: "32"
},
{
source: "22",
target: "33"
},
{
source: "23",
target: "28"
},
{
source: "23",
target: "27"
},
{
source: "23",
target: "29"
},
{
source: "23",
target: "30"
},
{
source: "23",
target: "31"
},
{
source: "23",
target: "33"
},
{
source: "32",
target: "33"
}]
};
focusNode = usingData.nodes[0];
focusNode.style = {
fill: '#0a0'
}
const graph = new G6.Graph({
container: 'mountNode',
width: 1000,
height: 600,
animate: true,
layout: {
type: 'radial',
center: [500, 300],
maxIteration: 1000,
focusNode,
unitRadius: 100,
linkDistance: 5,
preventOverlap: true,
nodeSize: 30,
sortBy: 'data'
},
modes: {
default: [ 'drag-node' ]
},
defaultNode: {
size: [20, 20],
color: 'steelblue',
style: {
lineWidth: 2,
fill: '#fff'
}
},
defaultEdge: {
size: 1,
color: '#e2e2e2',
style: {
endArrow: {
path: 'M 4,0 L -4,-4 L -4,4 Z',
d: 4
}
}
},
nodeStateStyle: {
selected: {
fill: 'steelblue'
}
}
});
graph.data(usingData);
graph.render();
graph.on('canvas:click', e => {
const newData = {
nodes: [
{
id: 'new-node-0',
x: 457,
y: 209
}, {
id: 'new-node-1',
x: 457,
y: 209
}, {
id: 'new-node-2',
x: 457,
y: 209
}, {
id: 'new-node-3',
x: 457,
y: 209
},
],
edges: [
{
source: 'new-node-0',
target: '0'
},
{
source: '1',
target: 'new-node-1'
},
{
source: '29',
target: 'new-node-2'
},
{
source: '11',
target: 'new-node-2'
},
{
source: '10',
target: 'new-node-3'
}
]
}
const allNodes = usingData.nodes.concat(newData.nodes);
const allEdges = usingData.edges.concat(newData.edges);
console.log(allNodes[1])
graph.changeData({ nodes: allNodes, edges: allEdges });
});
</script>
</body>
</html>

View File

@ -0,0 +1,526 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Radial Layout</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="../build/radial.js"></script>
<script>
const data = {
nodes: [{
id: "0",
label: "0",
sortAttr: 0,
sortAttr2: 'a'
},
{
id: "1",
label: "1",
sortAttr: 0,
sortAttr2: 'a'
},
{
id: "2",
label: "2",
sortAttr: 0,
sortAttr2: 'a'
},
{
id: "3",
label: "3",
sortAttr: 0,
sortAttr2: 'a'
},
{
id: "4",
label: "4",
sortAttr: 2,
sortAttr2: 'c'
},
{
id: "5",
label: "5",
sortAttr: 0,
sortAttr2: 'a'
},
{
id: "6",
label: "6",
sortAttr: 1,
sortAttr2: 'b'
},
{
id: "7",
label: "7",
sortAttr: 1,
sortAttr2: 'b'
},
{
id: "8",
label: "8",
sortAttr: 2,
sortAttr2: 'c'
},
{
id: "9",
label: "9",
sortAttr: 3,
sortAttr2: 'd'
},
{
id: "10",
label: "10",
sortAttr: 3,
sortAttr2: 'd'
},
{
id: "11",
label: "11",
sortAttr: 1,
sortAttr2: 'b'
},
{
id: "12",
label: "12",
sortAttr: 2,
sortAttr2: 'c'
},
{
id: "13",
label: "13",
sortAttr: 1,
sortAttr2: 'b'
},
{
id: "14",
label: "14",
sortAttr: 3,
sortAttr2: 'd'
},
{
id: "15",
label: "15",
sortAttr: 3,
sortAttr2: 'd'
},
{
id: "16",
label: "16",
sortAttr: 1,
sortAttr2: 'b'
},
{
id: "17",
label: "17",
sortAttr: 2,
sortAttr2: 'c'
},
{
id: "18",
label: "18",
sortAttr: 2,
sortAttr2: 'c'
},
{
id: "19",
label: "19",
sortAttr: 1,
sortAttr2: 'b'
},
{
id: "20",
label: "20",
sortAttr: 1,
sortAttr2: 'b'
},
{
id: "21",
label: "21",
sortAttr: 3,
sortAttr2: 'd'
},
{
id: "22",
label: "22",
sortAttr: 3,
sortAttr2: 'd'
},
{
id: "23",
label: "23",
sortAttr: 3,
sortAttr2: 'd'
},
{
id: "24",
label: "24",
sortAttr: 0,
sortAttr2: 'a'
},
{
id: "25",
label: "25",
sortAttr: 0,
sortAttr2: 'a'
},
{
id: "26",
label: "26",
sortAttr: 1,
sortAttr2: 'b'
},
{
id: "27",
label: "27",
sortAttr: 1,
sortAttr2: 'b'
},
{
id: "28",
label: "28",
sortAttr: 3,
sortAttr2: 'd'
},
{
id: "29",
label: "29",
sortAttr: 2,
sortAttr2: 'c'
},
{
id: "30",
label: "30",
sortAttr: 2,
sortAttr2: 'c'
},
{
id: "31",
label: "31",
sortAttr: 1,
sortAttr2: 'b'
},
{
id: "32",
label: "32",
sortAttr: 1,
sortAttr2: 'b'
},
{
id: "33",
label: "33",
sortAttr: 0,
sortAttr2: 'a'
}],
edges: [
{
source: "0",
target: "1"
},
{
source: "0",
target: "2"
},
{
source: "0",
target: "3"
},
{
source: "0",
target: "4"
},
{
source: "0",
target: "5"
},
{
source: "0",
target: "7"
},
{
source: "0",
target: "8"
},
{
source: "0",
target: "9"
},
{
source: "0",
target: "10"
},
{
source: "0",
target: "11"
},
{
source: "0",
target: "13"
},
{
source: "0",
target: "14"
},
{
source: "0",
target: "15"
},
{
source: "0",
target: "16"
},
{
source: "2",
target: "3"
},
{
source: "4",
target: "5"
},
{
source: "4",
target: "6"
},
{
source: "5",
target: "6"
},
{
source: "7",
target: "13"
},
{
source: "8",
target: "14"
},
{
source: "9",
target: "10"
},
{
source: "10",
target: "22"
},
{
source: "10",
target: "14"
},
{
source: "10",
target: "12"
},
{
source: "10",
target: "24"
},
{
source: "10",
target: "21"
},
{
source: "10",
target: "20"
},
{
source: "11",
target: "24"
},
{
source: "11",
target: "22"
},
{
source: "11",
target: "14"
},
{
source: "12",
target: "13"
},
{
source: "16",
target: "17"
},
{
source: "16",
target: "18"
},
{
source: "16",
target: "21"
},
{
source: "16",
target: "22"
},
{
source: "17",
target: "18"
},
{
source: "17",
target: "20"
},
{
source: "18",
target: "19"
},
{
source: "19",
target: "20"
},
{
source: "19",
target: "33"
},
{
source: "19",
target: "22"
},
{
source: "19",
target: "23"
},
{
source: "20",
target: "21"
},
{
source: "21",
target: "22"
},
{
source: "22",
target: "24"
},
{
source: "22",
target: "25"
},
{
source: "22",
target: "26"
},
{
source: "22",
target: "23"
},
{
source: "22",
target: "28"
},
{
source: "22",
target: "30"
},
{
source: "22",
target: "31"
},
{
source: "22",
target: "32"
},
{
source: "22",
target: "33"
},
{
source: "23",
target: "28"
},
{
source: "23",
target: "27"
},
{
source: "23",
target: "29"
},
{
source: "23",
target: "30"
},
{
source: "23",
target: "31"
},
{
source: "23",
target: "33"
},
{
source: "32",
target: "33"
}]
};
const usingData = data;
focusNode = usingData.nodes[0];
focusNode.style = {
fill: '#0a0'
}
const graph = new G6.Graph({
container: 'mountNode',
width: 1000,
height: 600,
layout: {
type: 'radial',
center: [500, 300],
maxIteration: 1000,
focusNode,
unitRadius: 100,
linkDistance: 10,
preventOverlap: true,
nodeSize: 30,
sortBy: 'sortAttr2',
sortStrength: 50
},
modes: {
default: [ 'drag-node' ]
},
// defaultNode: {
// size: [20, 20],
// color: 'steelblue',
// style: {
// lineWidth: 2,
// fill: '#fff'
// }
// },
defaultEdge: {
size: 1,
color: '#e2e2e2',
style: {
endArrow: {
path: 'M 4,0 L -4,-4 L -4,4 Z',
d: 4
}
}
},
nodeStateStyle: {
selected: {
fill: 'steelblue'
}
}
});
const colors = ['steelblue', 'green', 'pink', 'yellow'];
const colorsObj = { a: 'steelblue', b: 'green', c: 'pink', d: 'yellow' };
usingData.nodes.forEach(node => {
node.size = 20;
node.style = {
lineWidth: 2,
fill: '#fff',
stroke: colors[node.sortAttr2] || colorsObj[node.sortAttr2]
}
});
graph.data(usingData);
graph.render();
</script>
</body>
</html>

View File

@ -0,0 +1,541 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Radial Layout</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="../build/radial.js"></script>
<script>
const data = {
nodes: [{
id: "0",
label: "0"
},
{
id: "1",
label: "1"
},
{
id: "2",
label: "2"
},
{
id: "3",
label: "3"
},
{
id: "4",
label: "4"
},
{
id: "5",
label: "5"
},
{
id: "6",
label: "6"
},
{
id: "7",
label: "7"
},
{
id: "8",
label: "8"
},
{
id: "9",
label: "9"
},
{
id: "10",
label: "10"
},
{
id: "11",
label: "11"
},
{
id: "12",
label: "12"
},
{
id: "13",
label: "13"
},
{
id: "14",
label: "14"
},
{
id: "15",
label: "15"
},
{
id: "16",
label: "16"
},
{
id: "17",
label: "17"
},
{
id: "18",
label: "18"
},
{
id: "19",
label: "19"
},
{
id: "20",
label: "20"
},
{
id: "21",
label: "21"
},
{
id: "22",
label: "22"
},
{
id: "23",
label: "23"
},
{
id: "24",
label: "24"
},
{
id: "25",
label: "25"
},
{
id: "26",
label: "26"
},
{
id: "27",
label: "27"
},
{
id: "28",
label: "28"
},
{
id: "29",
label: "29"
},
{
id: "30",
label: "30"
},
{
id: "31",
label: "31"
},
{
id: "32",
label: "32"
},
{
id: "33",
label: "33"
}],
edges: [{
source: "0",
target: "1"
},
{
source: "0",
target: "2"
},
{
source: "0",
target: "3"
},
{
source: "0",
target: "4"
},
{
source: "0",
target: "5"
},
{
source: "0",
target: "7"
},
{
source: "0",
target: "8"
},
{
source: "0",
target: "9"
},
{
source: "0",
target: "10"
},
{
source: "0",
target: "11"
},
{
source: "0",
target: "13"
},
{
source: "0",
target: "14"
},
{
source: "0",
target: "15"
},
{
source: "0",
target: "16"
},
{
source: "2",
target: "3"
},
{
source: "4",
target: "5"
},
{
source: "4",
target: "6"
},
{
source: "5",
target: "6"
},
{
source: "7",
target: "13"
},
{
source: "8",
target: "14"
},
{
source: "9",
target: "10"
},
{
source: "10",
target: "22"
},
{
source: "10",
target: "14"
},
{
source: "10",
target: "12"
},
{
source: "10",
target: "24"
},
{
source: "10",
target: "21"
},
{
source: "10",
target: "20"
},
{
source: "11",
target: "24"
},
{
source: "11",
target: "22"
},
{
source: "11",
target: "14"
},
{
source: "12",
target: "13"
},
{
source: "16",
target: "17"
},
{
source: "16",
target: "18"
},
{
source: "16",
target: "21"
},
{
source: "16",
target: "22"
},
{
source: "17",
target: "18"
},
{
source: "17",
target: "20"
},
{
source: "18",
target: "19"
},
{
source: "19",
target: "20"
},
{
source: "19",
target: "33"
},
{
source: "19",
target: "22"
},
{
source: "19",
target: "23"
},
{
source: "20",
target: "21"
},
{
source: "21",
target: "22"
},
{
source: "22",
target: "24"
},
{
source: "22",
target: "25"
},
{
source: "22",
target: "26"
},
{
source: "22",
target: "23"
},
{
source: "22",
target: "28"
},
{
source: "22",
target: "30"
},
{
source: "22",
target: "31"
},
{
source: "22",
target: "32"
},
{
source: "22",
target: "33"
},
{
source: "23",
target: "28"
},
{
source: "23",
target: "27"
},
{
source: "23",
target: "29"
},
{
source: "23",
target: "30"
},
{
source: "23",
target: "31"
},
{
source: "23",
target: "33"
},
{
source: "32",
target: "33"
}]
};
const testdata = {
nodes: [{
id: "22018013015657",
label: "胡爱春",
nodeType: "Person"
},
{
id: "22017011813245",
label: "李肖远",
nodeType: "Person"
},
{
id: "22018013116039",
label: "赵龙",
nodeType: "Person"
},
{
id: "22018013015654",
label: "赵亚东",
nodeType: "Person"
},
{
id: "22018013015696",
label: "何二磊",
nodeType: "Person"
}],
edges: [{
target: "22018013116039",
edgeType: "Person2Person#Guarantee",
label: "担保(保证)",
properties: {},
source: "22018013015654",
timestamp: 1518019554489
},
{
target: "22017011813245",
edgeType: "Person2Person#Guarantee",
label: "担保(保证)",
properties: {},
source: "22018013015654",
timestamp: 1518034073051
},
{
target: "22018013015696",
edgeType: "Person2Person#Guarantee",
label: "担保(保证)",
properties: {},
source: "22018013015654",
timestamp: 1518102589066
},
{
target: "22018013015654",
edgeType: "Person2Person#Guarantee",
label: "担保(保证)",
properties: {},
source: "22018013015696",
timestamp: 1518028333742
},
{
target: "22018013015696",
edgeType: "Person2Person#Guarantee",
label: "担保(保证)",
properties: {},
source: "22018013116039",
timestamp: 1518037335045
},
{
target: "22018013015654",
edgeType: "Person2Person#Guarantee",
label: "担保(保证)",
properties: {},
source: "22017011813245",
timestamp: 1518102134180
},
{
target: "22018013015654",
edgeType: "Person2Person#Guarantee",
label: "担保(保证)",
properties: {},
source: "22018013116039",
timestamp: 1518037898347
}],
queryResult: "",
graphView: true
};
const usingData = data;
focusNode = usingData.nodes[0];
focusNode.style = {
fill: '#0a0'
}
const graph = new G6.Graph({
container: 'mountNode',
width: 1000,
height: 600,
layout: {
type: 'radial',
center: [500, 300],
maxIteration: 10,
focusNode,
unitRadius: 100,
linkDistance: 50,
preventOverlap: true,
nodeSize: 30,
sortBy: 'data'
},
modes: {
default: [{
type:
'brush-select',
onSelect(nodes) {
console.log('selected:', nodes);
},
onDeselect(nodes) {
console.log('deselect', nodes);
}
},
'drag-node']
},
defaultNode: {
size: [20, 20],
color: 'steelblue',
style: {
lineWidth: 2,
fill: '#fff'
}
},
defaultEdge: {
size: 1,
color: '#e2e2e2',
style: {
endArrow: {
path: 'M 4,0 L -4,-4 L -4,4 Z',
d: 4
}
}
},
nodeStateStyle: {
selected: {
fill: 'steelblue'
}
}
});
graph.data(usingData);
graph.render();
</script>
</body>
</html>

View File

@ -59,7 +59,6 @@
container: 'mountNode',
width: 500,
height: 500,
pixelRatio: 2,
plugins: [minimap],
modes: {
default: [{

419
demos/layout-random.html Normal file
View File

@ -0,0 +1,419 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MDS Layout</title>
</head>
<body>
<div id="mountNode"></div>
<script src="../build/g6.js"></script>
<script>
const data = {
"nodes": [
{
"id": "0",
"label": "0"
},
{
"id": "1",
"label": "1"
},
{
"id": "2",
"label": "2"
},
{
"id": "3",
"label": "3"
},
{
"id": "4",
"label": "4"
},
{
"id": "5",
"label": "5"
},
{
"id": "6",
"label": "6"
},
{
"id": "7",
"label": "7"
},
{
"id": "8",
"label": "8"
},
{
"id": "9",
"label": "9"
},
{
"id": "10",
"label": "10"
},
{
"id": "11",
"label": "11"
},
{
"id": "12",
"label": "12"
},
{
"id": "13",
"label": "13"
},
{
"id": "14",
"label": "14"
},
{
"id": "15",
"label": "15"
},
{
"id": "16",
"label": "16"
},
{
"id": "17",
"label": "17"
},
{
"id": "18",
"label": "18"
},
{
"id": "19",
"label": "19"
},
{
"id": "20",
"label": "20"
},
{
"id": "21",
"label": "21"
},
{
"id": "22",
"label": "22"
},
{
"id": "23",
"label": "23"
},
{
"id": "24",
"label": "24"
},
{
"id": "25",
"label": "25"
},
{
"id": "26",
"label": "26"
},
{
"id": "27",
"label": "27"
},
{
"id": "28",
"label": "28"
},
{
"id": "29",
"label": "29"
},
{
"id": "30",
"label": "30"
},
{
"id": "31",
"label": "31"
},
{
"id": "32",
"label": "32"
},
{
"id": "33",
"label": "33"
}],
"edges": [{
"source": "0",
"target": "1"
},
{
"source": "0",
"target": "2"
},
{
"source": "0",
"target": "3"
},
{
"source": "0",
"target": "4"
},
{
"source": "0",
"target": "5"
},
{
"source": "0",
"target": "7"
},
{
"source": "0",
"target": "8"
},
{
"source": "0",
"target": "9"
},
{
"source": "0",
"target": "10"
},
{
"source": "0",
"target": "11"
},
{
"source": "0",
"target": "13"
},
{
"source": "0",
"target": "14"
},
{
"source": "0",
"target": "15"
},
{
"source": "0",
"target": "16"
},
{
"source": "2",
"target": "3"
},
{
"source": "4",
"target": "5"
},
{
"source": "4",
"target": "6"
},
{
"source": "5",
"target": "6"
},
{
"source": "7",
"target": "13"
},
{
"source": "8",
"target": "14"
},
{
"source": "9",
"target": "10"
},
{
"source": "10",
"target": "22"
},
{
"source": "10",
"target": "14"
},
{
"source": "10",
"target": "12"
},
{
"source": "10",
"target": "24"
},
{
"source": "10",
"target": "21"
},
{
"source": "10",
"target": "20"
},
{
"source": "11",
"target": "24"
},
{
"source": "11",
"target": "22"
},
{
"source": "11",
"target": "14"
},
{
"source": "12",
"target": "13"
},
{
"source": "16",
"target": "17"
},
{
"source": "16",
"target": "18"
},
{
"source": "16",
"target": "21"
},
{
"source": "16",
"target": "22"
},
{
"source": "17",
"target": "18"
},
{
"source": "17",
"target": "20"
},
{
"source": "18",
"target": "19"
},
{
"source": "19",
"target": "20"
},
{
"source": "19",
"target": "33"
},
{
"source": "19",
"target": "22"
},
{
"source": "19",
"target": "23"
},
{
"source": "20",
"target": "21"
},
{
"source": "21",
"target": "22"
},
{
"source": "22",
"target": "24"
},
{
"source": "22",
"target": "25"
},
{
"source": "22",
"target": "26"
},
{
"source": "22",
"target": "23"
},
{
"source": "22",
"target": "28"
},
{
"source": "22",
"target": "30"
},
{
"source": "22",
"target": "31"
},
{
"source": "22",
"target": "32"
},
{
"source": "22",
"target": "33"
},
{
"source": "23",
"target": "28"
},
{
"source": "23",
"target": "27"
},
{
"source": "23",
"target": "29"
},
{
"source": "23",
"target": "30"
},
{
"source": "23",
"target": "31"
},
{
"source": "23",
"target": "33"
},
{
"source": "32",
"target": "33"
}]
};
const graph = new G6.Graph({
container: 'mountNode',
width: 1000,
height: 600,
fitView: true,
defaultNode: {
size: [20, 20],
color: 'steelblue'
},
defaultEdge: {
size: 1,
color: '#e2e2e2'
}
});
graph.data({
nodes: data.nodes,
edges: data.edges.map((edge, i) => {
edge.id = 'edge' + i;
return Object.assign({},
edge);
})
});
graph.render();
</script>
</body>
</html>

View File

@ -76,7 +76,6 @@
container: 'mountNode',
width: 500,
height: 500,
pixelRatio: 2,
linkCenter: true,
modes: {
default: [{

View File

@ -669,7 +669,6 @@
onWheel: ev => {
if (ev.ctrlKey) {
const canvas = graph.get("canvas");
const pixelRatio = canvas.get("pixelRatio");
const point = canvas.getPointByClient(ev.clientX, ev.clientY);
let ratio = graph.getZoom();
if (ev.wheelDelta > 0) {
@ -678,8 +677,8 @@
ratio = ratio - ratio * 0.05;
}
graph.zoomTo(ratio, {
x: point.x / pixelRatio,
y: point.y / pixelRatio
x: point.x,
y: point.y
});
} else {
const x = ev.deltaX || ev.movementX;

View File

@ -62,7 +62,6 @@
container: 'mountNode',
width: 500,
height: 500,
pixelRatio: 2,
renderer: 'svg',
modes: {
default: ['collapse-expand', 'drag-canvas']

View File

@ -5,7 +5,7 @@ order: 5
Behavior is the compound interactions in G6. In general, a Behavior includes one or more event listeners and a set of item operations.
By default, Behavior has three callbacks: `shouldBegin`, `shouldUpdate`, and `shouldEnd`, representing the beginning of the behavior, whether update the items, the ending of the behavior respectively. If they return `false`, the default behavior will be prevented.
By default, Behavior has three callbacks: `shouldBegin`, `shouldUpdate`, and `shouldEnd`, representing the beginning of the behavior, whether to update the items, the ending of the behavior respectively. If they return `false`, the default behavior will be prevented.
## Usage
```javascript
@ -30,9 +30,9 @@ G6.registerBehavior('behaviorName', {
```
## getEvents()
Define and handle events when user custom a Behavior.
Define and handle events when user customize a Behavior.
The usage of `getEvents()` can be refered to [Event](./Event)。
The usage of `getEvents()` can be refered to [Event](/en/docs/api/Event)。
**Usage**
```javascript
@ -74,7 +74,7 @@ G6.registerBehavior('behaviorName', {
| removed | Boolean | Whether the target is removed / destroyed. |
| timeStamp | Number | The time stamp. |
| bubbles | Boolean | Whether it is a bubbled event. |
| defaultPrevented | Boolean | Whether prevent the default event. |
| defaultPrevented | Boolean | Whether to prevent the default event. |
| cancelable | Boolean | Whether it is cancelable. |
@ -117,7 +117,7 @@ G6.registerBehavior('behaviorName', {
```
## shouldBegin(evt)
Whether prevent the behavior. Return `true` by default, which means do not prevent the behavior. User should call it by themselves.
Whether to prevent the behavior. Return `true` by default, which means do not prevent the behavior. User should call it by themselves.
**Usage**
```javascript
@ -130,7 +130,7 @@ G6.registerBehavior('behaviorName', {
```
## shouldUpdate(evt)
Whether update the data and the view. Returns `true` by default, which means allow updating.
Whether to update the data and the view. Returns `true` by default, which means allow updating.
**Usage**
```javascript
@ -138,7 +138,6 @@ const graph = new G6.Graph({
container: 'mountNode',
width: 500,
height: 500,
pixelRatio: 2,
modes: {
default: [ 'drag-canvas', {
type: 'self-behavior',
@ -154,4 +153,4 @@ const graph = new G6.Graph({
```
## shouldEnd(evt)
Whether end the behavior. Returns `true` by default.
Whether to end the behavior. Returns `true` by default.

View File

@ -32,7 +32,7 @@ G6.registerBehavior('behaviorName', {
## getEvents()
自定义 Behavior 时,定义事件及处理事件的方法。
`getEvents()` 方法中可以使用的事件请参考[Event文档](./Event)。
`getEvents()` 方法中可以使用的事件请参考[Event文档](/zh/docs/api/Event)。
**用法**
```javascript
@ -138,7 +138,6 @@ const graph = new G6.Graph({
container: 'mountNode',
width: 500,
height: 500,
pixelRatio: 2,
modes: {
default: [ 'drag-canvas', {
type: 'self-behavior',

View File

@ -9,15 +9,15 @@ This document will introduce custom mechanism in G6, including custom node, cust
When the built-in nodes cannot satisfy your requirments, custom a type of node by `G6.registerNode(nodeName, options, extendedNodeName)`.
**Parameters**
### Parameters
| Name | Type | Required | Description |
| -------------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| -------------- | ------ | -------- | ----------------------------------------------------------------- |
| nodeName | String | true | The unique name of the custom node. |
| options | Object | true | The configurations of custom node, include functions of complete life cycles. Please refer to [Shape](./Shape)。 |
| extendNodeName | String | false | Specifies the inherited node type of the custom node. Declare this attribute if you want to extend a built-in node. [Built-in Nodes](/en/docs/manual/middle/elements/nodes/defaultNode) |
| options | Object | true | The configurations of custom node, include functions of complete life cycles. Please refer to [Shape API](/en/docs/api/Shape). |
| extendNodeName | String | false | Specifies the inherited node type of the custom node. Declare this property if you want to extend a built-in node. [Built-in Nodes](/en/docs/manual/middle/elements/nodes/defaultNode) document. |
**Usage**
### Usage
```javascript
G6.registerNode(
@ -51,7 +51,7 @@ G6.registerNode(
*/
afterUpdate(cfg, node) {},
/**
* After [`graph.setItemState(item, state, value)`] is called, this function will do some responses.
* After graph.setItemState(item, state, value) is called, this function will do some responses.
* @param {String} name The name of state
* @param {Object} value The value of the state
* @param {Node} node The node
@ -72,15 +72,15 @@ G6.registerNode(
When the built-in edges cannot satisfy your requirments, custom a type of edge by `G6.registerEdge(edgeName, options, extendedEdgeName)`.
**Parameters**
### Parameters
| Name | Type | Required | Description |
| -------------- | ------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| -------------- | ------ | -------- | --------------------------------------- |
| edgeName | String | true | The unique name of the custom edge. |
| options | Object | true | The configurations of custom edge, include functions of complete life cycles. Please refer to [Shape](/zh/docs/api/Shape)。 |
| extendEdgeName | String | false | Specifies the inherited node type of the custom node. Declare this attribute if you want to extend the a built-in edge. [Built-in Edges](/zh/docs/manual/middle/elements/defaultEdge)。 |
| options | Object | true | The configurations of custom edge, include functions of complete life cycles. Please refer to [Shape API](/en/docs/api/Shape). |
| extendEdgeName | String | false | Specifies the inherited node type of the custom node. Declare this property if you want to extend the a built-in edge. [Built-in Edges](/en/docs/manual/middle/elements/edges/defaultEdge) document. |
**Usage**
### Usage
```javascript
G6.registerEdge(
@ -129,14 +129,14 @@ G6.registerEdge(
When the built-in Behaviors cannot satisfy your requirments, custom a type of Behavior by `G6.registerBehavior(behaviorName, behavior)`.
**Parameters**
### Parameters
| Name | Type | Required | Description |
| ------------ | ------ | -------- | ----------------------------------------------------------------------------------------------------------------------------- |
| behaviorName | String | true | The name of custom Behavior |
| behavior | Object | true | The configurations of custom Behavior. For more information, please refer to [Behavior](/en/docs/api/Behavior)。 |
| ------------ | ------ | -------- | ------------------------------------------------------- |
| behaviorName | String | true | The name of custom Behavior. |
| behavior | Object | true | The configurations of custom Behavior. For more information, please refer to [Behavior API](/en/docs/api/Behavior). |
**Usage**
### Usage
```javascript
// Custom a type of Behavior
@ -185,14 +185,14 @@ G6.registerBehavior('behaviorName', {
When the built-in Layouts cannot satisfy your requirments, custom a type of Layout by `G6.registerLayout(layoutName, layout)`.
**Parameters**
### Parameters
| Name | Type | Required | Description |
| ---------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------- |
| ---------- | ------ | -------- | ----------------------------------------------- |
| layoutName | String | true | The name of the custom layout. |
| layout | Object | true | The configurations of the custom layout. For more information, please refer to [Layout](/en/docs/manual/middle/layout)。 |
| layout | Object | true | The configurations of the custom layout. For more information, please refer to [Layout API](/en/docs/manual/middle/layout). |
**Usage**
### Usage
```javascript
G6.registerLayout('layoutName', {

View File

@ -9,15 +9,15 @@ order: 10
当内置节点不满足需求时,可以通过 `G6.registerNode(nodeName, options, extendNodeName)` 方法自定义节点。
**参数**
### 参数
| 名称 | 类型 | 是否必选 | 描述 |
| -------------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| -------------- | ------ | -------- | ---------------------------------------- |
| nodeName | String | true | 自定义节点名称,需保持唯一性。 |
| options | Object | true | 自定义节点时的配置项,配置项中包括完整的生命周期方法,具体请参考:[Shape 文档](./Shape)。 |
| extendNodeName | String | false | 自定义节点时可基于内置节点进行定义,该字段表示内置节点名称,所有内置节点请参考:[内置节点](/zh/docs/manual/middle/elements/nodes/defaultNode)。 |
| options | Object | true | 自定义节点时的配置项,配置项中包括完整的生命周期方法,具体请参考:[Shape API](/zh/docs/api/Shape)。 |
| extendNodeName | String | false | 自定义节点时可基于内置节点进行定义,该字段表示内置节点名称,所有内置节点请参考:[内置节点](/zh/docs/manual/middle/elements/nodes/defaultNode) 教程。 |
**用法**
### 用法
```javascript
G6.registerNode(
@ -27,7 +27,7 @@ G6.registerNode(
* 绘制节点,包含文本
* @param {Object} cfg 节点的配置项
* @param {G.Group} group 节点的容器
* @return {G.Shape} 绘制的图形通过node.get('keyShape') 可以获取到
* @return {G.Shape} 绘制的图形,通过 node.get('keyShape') 可以获取到
*/
draw(cfg, group) {},
/**
@ -59,9 +59,9 @@ G6.registerNode(
*/
setState(name, value, node) {},
/**
* 获取锚点(相关边的连点)
* 获取锚点(相关边的连点)
* @param {Object} cfg 节点的配置项
* @return {Array|null} 锚点的数组,如果为 null则没有控制
* @return {Array|null} 锚点(相关边的连入点)的数组,如果为 null则没有锚
*/
getAnchorPoints(cfg) {},
},
@ -73,15 +73,15 @@ G6.registerNode(
当内置的边不能满足需求时,可以通过 `registerEdge(edgeName, options, extendEdgeName)` 方法注册自定义的边。
**参数**
### 参数
| 名称 | 类型 | 是否必选 | 描述 |
| -------------- | ------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| -------------- | ------ | -------- | -------------------------------------------------- |
| edgeName | String | true | 自定义边的名称 |
| options | Object | true | 自定义边时的配置项,配置项中包括完整的生命周期方法,具体请参考:[Shape 文档](/zh/docs/api/Shape)。 |
| extendEdgeName | String | false | 自定义边时可基于内置边进行定义,该字段表示内置边的名称,所有内置边请参考:[内置边](/zh/docs/manual/middle/elements/defaultEdge)。 |
| options | Object | true | 自定义边时的配置项,配置项中包括完整的生命周期方法,具体请参考:[Shape API](/zh/docs/api/Shape)。 |
| extendEdgeName | String | false | 自定义边时可基于内置边进行定义,该字段表示内置边的名称,所有内置边请参考:[内置边](/zh/docs/manual/middle/elements/edges/defaultEdge) 教程。 |
**用法**
### 用法
```javascript
G6.registerEdge(
@ -91,7 +91,7 @@ G6.registerEdge(
* 绘制边,包含文本
* @param {Object} cfg 边的配置项
* @param {G.Group} group 边的容器
* @return {G.Shape} 绘制的图形通过node.get('keyShape') 可以获取到
* @return {G.Shape} 绘制的图形,通过 node.get('keyShape') 可以获取到
*/
draw(cfg, group) {},
/**
@ -131,14 +131,14 @@ G6.registerEdge(
当内置的 Behavior 不能满足需求时,使用 `registerBehavior(behaviorName, behavior)` 方法注册自定义的交互行为。
**参数**
### 参数
| 名称 | 类型 | 是否必选 | 描述 |
| ------------ | ------ | -------- | ----------------------------------------------------------------------------------------------------------------------------- |
| behaviorName | String | true | 自定义 Behavior 的名称 |
| behavior | Object | true | 自定义 behavior 时的配置项,配置项中包括的方法及作用具体请参考:[Behavior 文档](/zh/docs/api/Behavior)。 |
| ------------ | ------ | -------- | ----------------------------------------------------------------- |
| behaviorName | String | true | 自定义 Behavior 的名称 |
| behavior | Object | true | 自定义 behavior 时的配置项,配置项中包括的方法及作用具体请参考:[Behavior API](/zh/docs/api/Behavior)。 |
**用法**
### 用法
```javascript
// 注册自定义 Behavior
@ -186,14 +186,14 @@ G6.registerBehavior('behaviorName', {
当内置布局不满足需求时,可以通过 `G6.registerLayout(layoutName, layout)` 方法自定义布局。
**参数**
### 参数
| 名称 | 类型 | 是否必选 | 描述 |
| ---------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------- |
| layoutName | String | true | 自定义布局名称 |
| layout | Object | true | 自定义布局的配置项,配置项中包括的方法及作用具体请参考:[Layout 文档](/zh/docs/manual/middle/layout)。 |
| ---------- | ------ | -------- | --------------------------------------- |
| layoutName | String | true | 自定义布局名称 |
| layout | Object | true | 自定义布局的配置项,配置项中包括的方法及作用具体请参考:[Layout API](/zh/docs/manual/middle/layout)。 |
**用法**
### 用法
```javascript
G6.registerLayout('layoutName', {

View File

@ -3,7 +3,7 @@ title: Event
order: 6
---
The parameters of callbacks for common events, Node events, and Edge events are described in [Behavior](./Behavior).
The parameters of callbacks for common events, Node events, and Edge events are described in [Behavior API](/en/docs/api/Behavior).
## Common Event
@ -18,7 +18,7 @@ The parameters of callbacks for common events, Node events, and Edge events are
| mouseleave | Activated when the mouse leaves an item. **This is not a bubbled event**, which means this event will not be activated when the mouse leaves the descendant items. |
| mousedown | Activated when the left or right button is clicked down. It cannot be activated by keyboard. |
| mouseup | Activated when the left or right button is released. It cannot be activated by keyboard. |
| contextmenu | Open the context menu when user clicks the right button of mouse. |
| contextmenu | Open the context menu when user clicks the right button of mouse. [Demo](/en/examples/tool/contextMenu). |
| dragstart | Activated when user begins to drag. This event is applied on a dragged item. |
| drag | Activated during the dragging process. This event is applied on a dragged item. |
| dragend | Activated when user stops dragging. This event is applied on a dragged item. |
@ -45,7 +45,7 @@ The parameters of callbacks for common events, Node events, and Edge events are
| node:mouseleave | Activated when the mouse leaves the node. |
| node:mousedown | Activated when the left or right button is clicked down on the node. It cannot be activated by keyboard. |
| node:mouseup | Activated when the left or right button is released on the node. It cannot be activated by keyboard. |
| node:contextmenu | Open the context menu when user clicks the right button of mouse on the node. |
| node:contextmenu | Open the context menu when user clicks the right button of mouse on the node. [Demo](/en/examples/tool/contextMenu). |
| node:dragstart | Activated when user begins to drag the node. This event is applied on the dragged node. |
| node:drag | Activated during the dragging process on the node. This event is applied on the dragged node. |
| node:dragend | Activated when user stops dragging on the node. This event is applied on the dragged node. |
@ -67,7 +67,7 @@ The parameters of callbacks for common events, Node events, and Edge events are
| edge:mouseleave | Activated when the mouse leaves the edge. |
| edge:mousedown | Activated when the left or right button is clicked down on the edge. It cannot be activated by keyboard. |
| edge:mouseup | Activated when the left or right button is released on the edge. It cannot be activated by keyboard. |
| edge:contextmenu | Open the context menu when user clicks the right button of mouse on the edge. |
| edge:contextmenu | Open the context menu when user clicks the right button of mouse on the edge. [Demo](/en/examples/tool/contextMenu). |
## Canvas Event
@ -84,7 +84,7 @@ The parameters of callbacks for common events, Node events, and Edge events are
| canvas:mousedown | Activated when the left or right button is clicked down on the canvas. It cannot be activated by keyboard. |
| canvas:mouseup | Activated when the left or right button is released on the canvas. It cannot be activated by keyboard. |
| canvas:contextmenu | Open the context menu when user clicks the right button of mouse on the canvas. |
| canvas:dragstart | Activated when user begins to drag the canvas. This event is applied on the dragged canvas. |
| canvas:dragstart | Activated when user begins to drag the canvas. This event is applied on the dragged canvas. [Demo](/en/examples/tool/contextMenu). |
| canvas:drag | Activated during the dragging process on the canvas. This event is applied on the dragged canvas. |
| canvas:dragend | Activated when user stops dragging on the canvas. This event is applied on the dragged canvas. |
| canvas:dragenter | Activated when user drags the canvas into a target item. This event is applied on the target item. |

View File

@ -3,7 +3,7 @@ title: Event
order: 6
---
通用事件、Node 事件、Edge 事件及 Canvas 事件回调的参数请参考[Behavior 文档](./Behavior)。
通用事件、Node 事件、Edge 事件及 Canvas 事件回调的参数请参考 [Behavior API](/zh/docs/api/Behavior)。
## 通用事件
@ -18,7 +18,7 @@ order: 6
| mouseleave | 鼠标移出元素范围时触发,**该事件不冒泡**,即鼠标移到其后代元素时不会触发 |
| mousedown | 鼠标按钮被按下(左键或者右键)时触发,不能通过键盘触发 |
| mouseup | 鼠标按钮被释放弹起时触发,不能通过键盘触发 |
| contextmenu | 用户右击鼠标时触发并打开上下文菜单 |
| contextmenu | 用户右击鼠标时触发并打开上下文菜单,见 [Demo](/zh/examples/tool/contextMenu) |
| dragstart | 当拖拽元素开始被拖拽的时候触发的事件,此事件作用在被拖曳元素上 |
| drag | 当拖拽元素在拖动过程中时触发的事件,此事件作用于被拖拽元素上 |
| dragend | 当拖拽完成后触发的事件,此事件作用在被拖曳元素上 |
@ -28,7 +28,7 @@ order: 6
| keydown | 按下键盘键触发该事件 |
| keyup | 释放键盘键触发该事件 |
| touchstart | 当手指触摸屏幕时候触发,即使已经有一个手指放在屏幕上也会触发 |
| touchmove | 当手指在屏幕上滑动的时候连续地触发。在这个事件发生期间,调用 preventDefault() 事件可以阻止滚动。 |
| touchmove | 当手指在屏幕上滑动的时候连续地触发。在这个事件发生期间,调用 `preventDefault()` 事件可以阻止滚动。 |
| touchend | 当手指从屏幕上离开的时候触发 |
@ -45,7 +45,7 @@ order: 6
| node:mouseleave | 鼠标移出节点时触发 |
| node:mousedown | 鼠标按钮在节点上按下(左键或者右键)时触发,不能通过键盘触发 |
| node:mouseup | 节点上按下的鼠标按钮被释放弹起时触发,不能通过键盘触发 |
| node:contextmenu | 用户在节点上右击鼠标时触发并打开右键菜单 |
| node:contextmenu | 用户在节点上右击鼠标时触发并打开右键菜单,见 [Demo](/zh/examples/tool/contextMenu) |
| node:dragstart | 当节点开始被拖拽的时候触发的事件,此事件作用在被拖曳节点上 |
| node:drag | 当节点在拖动过程中时触发的事件,此事件作用于被拖拽节点上 |
| node:dragend | 当拖拽完成后触发的事件,此事件作用在被拖曳节点上 |
@ -67,7 +67,7 @@ order: 6
| edge:mouseleave | 鼠标移出边时触发 |
| edge:mousedown | 鼠标按钮在边上按下(左键或者右键)时触发,不能通过键盘触发 |
| edge:mouseup | 边上按下的鼠标按钮被释放弹起时触发,不能通过键盘触发 |
| edge:contextmenu | 用户在边上右击鼠标时触发并打开右键菜单 |
| edge:contextmenu | 用户在边上右击鼠标时触发并打开右键菜单,见 [Demo](/zh/examples/tool/contextMenu) |
## Canvas事件
@ -83,7 +83,7 @@ order: 6
| canvas:mouseleave | 鼠标移出画布时触发 |
| canvas:mousedown | 鼠标按钮在画布上按下(左键或者右键)时触发,不能通过键盘触发 |
| canvas:mouseup | 画布上按下的鼠标按钮被释放弹起时触发,不能通过键盘触发 |
| canvas:contextmenu | 用户在画布上右击鼠标时触发并打开右键菜单 |
| canvas:contextmenu | 用户在画布上右击鼠标时触发并打开右键菜单,见 [Demo](/zh/examples/tool/contextMenu) |
| canvas:dragstart | 当画布开始被拖拽的时候触发的事件,此事件作用在被拖曳画布上 |
| canvas:drag | 当画布在拖动过程中时触发的事件,此事件作用于被拖拽画布上 |
| canvas:dragend | 当拖拽完成后触发的事件,此事件作用在被拖曳画布上 |

View File

@ -19,17 +19,17 @@ The life cycle of an instance of Graph is: Initialize -> Load data -> Render ->
| container | String|HTMLElement | The DOM container of graph, it can be the id of a DOM element or the an HTML node. |
| width | Number | undefined | The width of the canvas for graph with the unit 'px'. |
| height | Number | undefined | The height of the canvas for graph with the unit 'px'. |
| renderer | String | canvas | The engine for rendering. Options: 'canvas' or 'svg'. |
| fitView | Boolean | false | Whether fit the canvas to the view port. |
| renderer | String | canvas | The engine for rendering. Options: `'canvas'` or `'svg'`. |
| fitView | Boolean | false | Whether to fit the canvas to the view port. |
| fitViewPadding | Array | Number | Takes effect only when `fitView: true`. It is the padding between canvas and the border of view port.<br />- It can be a value, e.g. `fitViewPadding: 20`, which means the padding to the top, left, right, bottom are the same.<br />- Or an array, e.g. `fitViewPadding: [ 20, 40, 50, 20 ]`, the four values in the array indicate the padding to the top, right, bottom, left respectively. |
| groupByTypes | Boolean | true | Whether group the nodes and edges separately. When it is false, all the items (including nodes and edges) are in the same group, and the order/zindex of them are determined according to the order of their generation. |
| autoPaint | Boolean | true | Whether paint the graph automatically while item updated or view port changed. In order to enhance the performance, we recommend to turn off `antoPaint` when you are doing bulk operation on nodes or edges. This can be refered to [`setAutoPaint()`](#setautopaintauto). |
| groupByTypes | Boolean | true | Whether to group the nodes and edges separately. When it is false, all the items (including nodes and edges) are in the same group, and the order/zindex of them are determined according to the order of their generation. |
| autoPaint | Boolean | true | Whether to paint the graph automatically while item updated or view port changed. In order to enhance the performance, we recommend to turn off `antoPaint` when you are doing bulk operation on nodes or edges. This can be refered to [`setAutoPaint()`](#setautopaintauto). |
| modes | Object | | The interaction modes of this graph. Please refer to [Interaction Mode](/en/docs/manual/middle/states/mode) for detail。 |
| nodeStateStyles | Object | {} | The node styles on different states, e.g. hover, selected. It is a new feature of G6 3.1. |
| edgeStateStyles | Object | {} | The edge styles on different states, e.g. hover, selected. It is a new feature of G6 3.1. |
| defaultNode | Object | {} | Default node configurations in global, including shape, size, color and so on. Its priority is lower than the configurations in data. |
| defaultEdge | Object | {} | Default edge configurations in global, including shape, size, color and so on. Its priority is lower than the configurations in data. |
| plugins | Array | [] | Plugins for graph. Please refer to [plugin](/en/docs/manual/tutorial/plugins#插件) for detail.|
| plugins | Array | [] | Plugins for graph. Please refer to [Plugin](/en/docs/manual/tutorial/plugins##plugin) for detail.|
| animate | Boolean | false | Wheter activate the global animation. Which will take effect while changing layouts, changing data, and other global operations. |
| animateCfg | Object | | The configurations for global animation. Takes effect only when `animate: true`. |
| animateCfg.<br />onFrame | Function | null | The callback function for every frame of animation. The path of custom animation for node can be defined here. The nodes will move linearly when `onFrame` is null. |
@ -37,13 +37,12 @@ The life cycle of an instance of Graph is: Initialize -> Load data -> Render ->
| animateCfg.<br />easing | String | easeLinear | The easing function name of animation. Please refer to ease in d3. |
| minZoom | Number | 0.2 | The minimum zoom ratio. |
| maxZoom | Number | 10 | The maximum zoom ratio. |
| pixelRatio | Number | 1.0 | Pixel ratio. |
| groupType | String | circle | Group type for nodes. Options: 'circle' or 'rect' |
| groupType | String | circle | Group type for nodes. Options: `'circle'` or `'rect'`. |
| groupStyle | Object | | Group style for nodes, please refer to [Node Group](/en/docs/manual/middle/nodeGroup) for detail. |
| layout | Object | | Configurations for layout. The `type` in it is the name of layout method with the options: 'random', 'radial', 'mds', 'circular', 'fruchterman', 'force', 'dagre', 'concentric', 'grid'. For more configurations for different layout methods, please refer to  [Layout API](/en/docs/api/layout/Layout) |
| layout | Object | | Configurations for layout. The `type` in it is the name of layout method with the options: `'random'`, `'radial'`, `'mds'`, `'circular'`, `'fruchterman'`, `'force'`, `'dagre'`, `'concentric'`, `'grid'`. For more configurations for different layout methods, please refer to [Layout API](/en/docs/api/layout/Layout). |
⚠️**Attention:** In G6 3.1, we added two new configurations for graph: `nodeStateStyles` and `edgeStateStyles`. In the same time, we deleted `nodeStyle` and `edgeStyle` . To upgrate, replace `nodeStyle` with `nodeStateStyles`, and replace `edgeStyle` with `edgeStateStyles`, and keep the sub-configuration inside them.
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>Attention:</strong></span> In G6 3.1, we added two new configurations for graph: `nodeStateStyles` and `edgeStateStyles`. In the same time, we deleted `nodeStyle` and `edgeStyle` . To upgrate, replace `nodeStyle` with `nodeStateStyles`, and replace `edgeStyle` with `edgeStateStyles`, and keep the sub-configuration inside them.
**Usage**
@ -119,7 +118,7 @@ Render a node group according to the data.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| data | Object | true | The data to be rendered |
| groupType | string | true | Type of node group. Options: 'circle' or 'rect' |
| groupType | String | true | Type of node group. Options: `'circle'` or `'rect'` |
**Usage**
@ -271,8 +270,8 @@ Add item(node, edge, or group) to the graph.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | true | The type of the item. Options: 'node', 'edge', and 'group'. |
| model | Object | true | The data model of the item. When type = 'group', refer to [Create Node Group](/en/docs/manual/advanced/create-node-group) |
| type | String | true | The type of the item. Options: `'node'`, `'edge'`, and `'group'`. |
| model | Object | true | The data model of the item. When `type: 'group'`, refer to [Create Node Group](/en/docs/manual/advanced/create-node-group) |
**Usage**
@ -416,13 +415,13 @@ graph.setAutoPaint(autoPaint);
```
### setAutoPaint(auto)
Whether repaint the canvas automatically after updating or deleting items.
Whether to repaint the canvas automatically after updating or deleting items.
**Parameters**
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| auto | Boolean | true | Whether repaint the canvas automatically. |
| auto | Boolean | true | Whether to repaint the canvas automatically. |
**Usage**
@ -497,7 +496,7 @@ graph.on('node:dragend', e => {
### updateLayout(cfg)
Update the layout configurations.
1. If there is `type` in `cfg`, `type` is a String and it is different from current layout method, `updateLayout(cfg)` will change the layout method and relayout;
1. If there is `type` in `cfg`, `type` is a string and it is different from current layout method, `updateLayout(cfg)` will change the layout method and relayout;
1. If there is no `type` in `cfg`, `updateLayout(cfg)` will relayout with current layout method and new layout configurations.
**Parameters**
@ -611,7 +610,7 @@ This function will emit events `beforitemstatechange` and `afteritemstatechange`
| --- | --- | --- | --- |
| item | String / Object | true | The id or the instance of the item. |
| state | String | true | The value of state. State can be comstomized as selected, hover, actived, and so on. |
| enabled | Boolean | true | Whether activate the state. |
| enabled | Boolean | true | Whether to activate the state. |
**Usage**
@ -646,7 +645,7 @@ graph.clearItemStates(node);
### node(nodeFn)
Set the style and other configurations for each node.
⚠️**Attention:** this funcion must **be called before graph.render()**. It does not take effect otherwise.
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>Attention:</strong></span> this funcion must **be called before graph.render()**. It does not take effect otherwise.
**Parameters**
@ -674,7 +673,7 @@ graph.render()
### edge(edgeFn)
Set the style and other configurations for each edge.
⚠️**Attention:** this funcion must **be called before graph.render()**. It does not take effect otherwise.
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>Attention:</strong></span> this funcion must **be called before graph.render()**. It does not take effect otherwise.
**Parameters**
@ -770,7 +769,6 @@ const graph = new G6.Graph({
container: div,
width: 500,
height: 500,
pixelRatio: 2,
modes: {
default: [...],
custom: [...]
@ -820,7 +818,7 @@ Change the zoom ratio. The parameter ratio is the related ratio about the curren
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| ratio | Number | true | Zoom ratio.|
| center | Object | false | Zoom at the center with x and y. If the center is ignored, this operation will zoom the graph with the current graph center. |
| center | Object | false | Zoom at the `center` with `x` and `y`. If the `center` is ignored, this operation will zoom the graph with the current graph center. |
**Usage**
@ -840,7 +838,7 @@ Zoom the canvas at the center to a fixed ratio.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| toRatio | Number | true | Fixed zoom ratio. |
| center | Object | false | Zoom at the center with x and y. If the center is ignored, this operation will zoom the graph with the current graph center. |
| center | Object | false | Zoom at the `center` with `x` and `y`. If the `center` is ignored, this operation will zoom the graph with the current graph center. |
**Usage**
@ -954,7 +952,7 @@ Find single item according to a rule.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | true | Type of the item. Options: 'node', 'edge'. |
| type | String | true | Type of the item. Options: `'node'`, `'edge'`. |
| fn | Function | true | Rule for searching. |
@ -999,7 +997,7 @@ Find all the items that match the rule.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | true | The type of the item. Options: 'node', 'edge'. |
| type | String | true | The type of the item. Options: `'node'`, `'edge'`. |
| fn | Function | true | Rule for searching. |
@ -1023,7 +1021,7 @@ Find all the items whose value of state is true.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| type | String | true | The type of the item. Options: 'node', 'edge'. |
| type | String | true | The type of the item. Options: `'node'`, `'edge'`. |
| state | String | true | State for searching. |
@ -1065,7 +1063,7 @@ graph.save()
### getNodes()
Get all the node items in the graph.
⚠️**Attention:** it returns the items but not data models.
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>Attention:</strong></span> it returns the items but not data models.
**Return**
@ -1081,11 +1079,7 @@ const nodes = graph.getNodes()
### getEdges()
Get all the edge items in the graph.
<<<<<<< HEAD
⚠️**Attention:** it returns the items but not data models.
=======
Attention: it returns the items but not data models.
>>>>>>> feat: english version of API
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>Attention:</strong></span> it returns the items but not data models.
**Return**
@ -1101,7 +1095,7 @@ const edges = graph.getEdges()
## Coordinate Transformation
In this part, we will describe the methods about transformation between view port, canvas, and client coordinates. The relationships between them are shown below:
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*loahSq940hMAAAAAAAAAAABkARQnAQ' width=565 />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*M_xPSqLZYawAAAAAAAAAAABkARQnAQ' width=565 />
### getPointByClient(clientX, clientY)
Transform client/screen coordinates into view port coordinates.
@ -1140,7 +1134,7 @@ Transform view port coordinates into client/screen coordinates.
**Return**
- Type of the return value: Object;
- Includes x and y.
- Includes `x` and `y`.
**Usage**
@ -1197,7 +1191,7 @@ console.log('The x and y coordinates of canvas: ', point.x, point.y)
## Animation
### positionsAnimate()
Update the node positions according to the data model animatively.
Update the node positions according to the data model animatively. The `animateCfg` of the graph will be the animation configurations.
### stopAnimate()
Stop the animation on the canvas.
@ -1247,13 +1241,13 @@ graph.removePlugin(miniMap)
```
### get(key)
Get ant attribute of graph by key.
Get an property of graph by key.
**Parameters**
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| key | String | true | Key of the attribute. |
| key | String | true | Key of the property. |
**Usage**
@ -1270,14 +1264,14 @@ const autoPaint = graph.get('autoPaint')
```
### set(key, val)
Set the value to an attribute.
Set the value to an property.
**Parameters**
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| key | String | true | The key of the attribute. |
| val | String / Object | Array | true | The value of the attribute. |
| key | String | true | The key of the property. |
| val | String / Object / Array | true | The value of the property. |
**Usage**

View File

@ -28,7 +28,7 @@ Graph 的生命周期为:初始化—>加载数据—>渲染—>更新—>销
| edgeStateStyles | Object | {} | 各个状态下边的样式,例如 `hover`、`selected`3.1版本新增。 |
| defaultNode | Object | {} | 默认状态下节点的配置,比如 `shape`, `size`, `color`。会被写入的 data 覆盖。 |
| defaultEdge | Object | {} | 默认状态下边的配置,比如 `shape`, `size`, `color`。会被写入的 data 覆盖。 |
| plugins | Array | [] | 向 graph 注册插件。插件机制请见:[plugin](/zh/docs/manual/tutorial/plugins#插件) |
| plugins | Array | [] | 向 graph 注册插件。插件机制请见:[插件](/zh/docs/manual/tutorial/plugins#插件) |
| animate | Boolean | false | 是否启用全局动画。 |
| animateCfg | Object | | 动画配置项,仅在 `animate``true` 时有效。 |
| animateCfg.<br />onFrame | Function | null | 回调函数,用于自定义节点运动路径,为空时线性运动。 |
@ -36,13 +36,12 @@ Graph 的生命周期为:初始化—>加载数据—>渲染—>更新—>销
| animateCfg.<br />easing | String | easeLinear | 动画动效,可参见 d3 ease。 |
| minZoom | Number | 0.2 | 最小缩放比例 |
| maxZoom | Number | 10 | 最大缩放比例 |
| pixelRatio | Number | 1.0 | 像素比率 |
| groupType | String | circle | 节点分组类型,支持 circle 和 rect |
| groupStyle | Object | | groupStyle 用于指定分组的样式,详情参看[节点分组](/zh/docs/manual/middle/nodeGroup) |
| groupStyle | Object | | groupStyle 用于指定分组的样式,详情参看 [节点分组 Group](/zh/docs/manual/middle/nodeGroup) 教程 |
| layout | Object | | 布局配置项,使用 type 字段指定使用的布局方式type可取以下值random, radial, mds, circular, fruchterman, force, dagre各布局详细的配置请参考 [Layout API 文档](/zh/docs/api/layout/Layout) |
**重点说明**: G6 3.1 版本中实例化 Graph 时,新增了 `nodeStateStyles` 及 `edgeStateStyles` 两个配置项,删除了 `nodeStyle``edgeStyle` ,使用 3.1 以下版本的同学,只需要将 `nodeStyle` 改成 `nodeStateStyles` ,将 `edgeStyle` 改成 `edgeStateStyles` ,配置内容保持不变。
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>⚠️注意:</strong></span>6 3.1 版本中实例化 Graph 时,新增了 `nodeStateStyles` 及 `edgeStateStyles` 两个配置项,删除了 `nodeStyle``edgeStyle` ,使用 3.1 以下版本的同学,只需要将 `nodeStyle` 改成 `nodeStateStyles` ,将 `edgeStyle` 改成 `edgeStateStyles` ,配置内容保持不变。
**用法**
@ -118,7 +117,7 @@ graph.render()
| 名称 | 类型 | 是否必选 | 描述 |
| --- | --- | --- | --- |
| data | Object | true | 渲染图的数据 |
| groupType | string | true | group 类型,支持 circle、rect |
| groupType | string | true | group 类型,支持 `'circle'``'rect'` |
**用法**
@ -155,7 +154,7 @@ const data = {
]
};
// graph是Graph的实例
// graph Graph 的实例
graph.renderCustomGroup(data, "circle");
```
###
@ -237,7 +236,7 @@ graph.changeData(data)
| 名称 | 类型 | 是否必选 | 描述 |
| --- | --- | --- | --- |
| groupId | String | true | 分组ID |
| groupId | String | true | 分组 ID |
**用法**
@ -253,7 +252,7 @@ graph.collapseGroup('groupId')
| 名称 | 类型 | 是否必选 | 描述 |
| --- | --- | --- | --- |
| groupId | String | true | 分组ID |
| groupId | String | true | 分组 ID |
**用法**
@ -270,8 +269,8 @@ graph.expandGroup('groupId')
| 名称 | 类型 | 是否必选 | 描述 |
| --- | --- | --- | --- |
| type | String | true | 元素类型,可选值为 node、edge 和group |
| model | Object | true | 元素的数据模型,type = 'group' 时,参看[手动创建节点分组文档](/zh/docs/manual/advanced/create-node-group) |
| type | String | true | 元素类型,可选值为 `'node'``'edge'` `'group'` |
| model | Object | true | 元素的数据模型,`type: 'group'` 时,参看 [手动创建节点分组文档](/zh/docs/manual/advanced/create-node-group) |
**用法**
@ -446,7 +445,7 @@ graph.setAutoPaint(autoPaint);
## 布局
G6 3.1 内置了丰富的布局。关于如何使用 G6 中内置的布局,请参考 [Layout API文档](/zh/docs/api/layout/Layout)。
G6 3.1 内置了丰富的布局。关于如何使用 G6 中内置的布局,请参考 [Layout API](/zh/docs/api/layout/Layout)。
### layout()
重新以当前配置的属性进行一次布局。
@ -633,7 +632,7 @@ graph.setItemState('node1', 'selected', true);
| 名称 | 类型 | 是否必选 | 描述 |
| --- | --- | --- | --- |
| item | String / Object | true | 元素 ID 或元素实例 |
| states | String / Array | null  | false | 取值可以是单个状态值,也可以是状态值数组或 null当为 null 时,清除该元素的**第一个**状态。 |
| states | String / Array | null  | false | 取值可以是单个状态值,也可以是状态值数组或 `null`,当为 `null` 时,清除该元素的**第一个**状态。 |
**用法**
@ -776,7 +775,6 @@ const graph = new G6.Graph({
container: div,
width: 500,
height: 500,
pixelRatio: 2,
modes: {
default: [...],
custom: [...]
@ -793,7 +791,7 @@ graph.setMode('custom')
**返回值**
- 返回值类型:string
- 返回值类型:String
- 返回值表示当前的行为模式。
**用法**
@ -810,8 +808,8 @@ const mode = graph.getCurrentMode()
**返回值**
- 返回值类型:number
- 返回值表示当前视口的缩放比例, 默认值为 1。
- 返回值类型:Number
- 返回值表示当前视口的缩放比例, 默认值为 `1`
**用法**
@ -828,15 +826,15 @@ const zoom = graph.getZoom()
| 名称 | 类型 | 是否必选 | 描述 |
| --- | --- | --- | --- |
| ratio | Number | true | 缩放比例 |
| center | Object | false | 以 center 的 x、y 坐标为中心缩放,如果省略了 center 参数,则以元素当前位置为中心缩放 |
| center | Object | false | 以 `center``x``y` 坐标为中心缩放,如果省略了 `center` 参数,则以元素当前位置为中心缩放 |
**用法**
```javascript
// 以(100, 100)为中心点放大3倍
// 以 (100, 100) 为中心点放大3倍
graph.zoom(3, { x: 100, y: 100 });
// 以当前元素位置为中心缩小到0.5
// 以当前元素位置为中心,缩小到 0.5
graph.zoom(0.5)
```
@ -848,16 +846,16 @@ graph.zoom(0.5)
| 名称 | 类型 | 是否必选 | 描述 |
| --- | --- | --- | --- |
| toRatio | Number | true | 固定比例值 |
| center | Object | false | 以 center 的 x、y 坐标为中心缩放,如果省略了 center 参数,则以元素当前位置为中心缩放 |
| center | Object | false | 以 `center``x``y` 坐标为中心缩放,如果省略了 `center` 参数,则以元素当前位置为中心缩放 |
**用法**
```javascript
// 以(100, 100)为中心点放大3倍
// 以 (100, 100) 为中心点放大3倍
graph.zoomTo(3, { x: 100, y: 100 });
// 以当前元素位置为中心缩小到0.5
// 以当前元素位置为中心,缩小到 0.5
graph.zoomTo(0.5)
```
@ -962,7 +960,7 @@ graph.fitView([20, 10, 20, 15])
| 名称 | 类型 | 是否必选 | 描述 |
| --- | --- | --- | --- |
| type | String | true | 元素类型,可选值为 node、edge |
| type | String | true | 元素类型,可选值为 `'node'``'edge'` |
| fn | Function | true | 查找的规则 |
@ -1007,7 +1005,7 @@ const node = graph.findById('node')
| 名称 | 类型 | 是否必选 | 描述 |
| --- | --- | --- | --- |
| type | String | true | 元素类型,可选值为 node、edge |
| type | String | true | 元素类型,可选值为 `'node'``'edge'` |
| fn | Function | true | 查找的规则 |
@ -1031,8 +1029,8 @@ const nodes = graph.findAll('node', node => {
| 名称 | 类型 | 是否必选 | 描述 |
| --- | --- | --- | --- |
| type | String | true | 元素类型,可选值为 node、edge |
| state | String | true | 状态 |
| type | String | true | 元素类型,可选值为 `'node'``'edge'` |
| state | String | true | 状态名称 |
**返回值**
@ -1074,7 +1072,7 @@ graph.save()
### getNodes()
获取图中所有节点的实例。
注意:这里返回的是节点的实例,而不是节点的数据项。
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>⚠️注意:</strong></span>这里返回的是节点的实例,而不是节点的数据项。
**返回值**
@ -1090,7 +1088,7 @@ const nodes = graph.getNodes()
### getEdges()
获取图中所有边的实例。
注意:这里返回的是边的实例,而不是边的数据项。
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>⚠️注意:</strong></span>这里返回的是边的实例,而不是边的数据项。
**返回值**
@ -1128,7 +1126,7 @@ const edges = graph.getEdges()
```javascript
const point = graph.getPointByClient(e.clientX, e.clientY);
console.log('视口x/y坐标分别为:', point.x, point.y)
console.log('视口 x/y 坐标分别为:', point.x, point.y)
```
### getClientByPoint(x, y)
@ -1145,7 +1143,7 @@ console.log('视口x/y坐标分别为:', point.x, point.y)
**返回值**
- 返回值类型Object
- 包含的属性x 和 y 属性,分别表示屏幕/页面的 x、y 坐标。
- 包含的属性:`x``y` 属性,分别表示屏幕/页面的 x、y 坐标。
**用法**
@ -1202,7 +1200,7 @@ console.log('Canvas画布的x/y坐标分别为:', point.x, point.y)
## 动画
### positionsAnimate()
根据 Graph 上的 animateCfg 配置项,处理视口中节点的动画
根据当前数据中的节点位置,动画更新节点位置。将会使用 graph 上的 `animateCfg` 配置项作为动画行为的依据
### stopAnimate()
停止画布上的所有动画。
@ -1282,7 +1280,7 @@ const autoPaint = graph.get('autoPaint')
| 名称 | 类型 | 是否必选 | 描述 |
| --- | --- | --- | --- |
| key | String | true | 属性的键 |
| val | String / Object | Array | true | 属性的值 |
| val | String / Object / Array | true | 属性的值 |
**用法**

View File

@ -3,7 +3,7 @@ title: Graphics Group
order: 8
---
Graphics Group (hereinafter referred to as Group) in G6 is similar to [`<g>`](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g) [tag](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g) in [SVG](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g): Group a container of a group of graphics. The transformations on a Group such as clipping, rotating, zooming, and translating will be applied to all the children of the Group. The attributes like color and position will also be inherited by its children. Besides, Group can be nested for complicated objects. For more information about Group, please refer to《[Graphics Group](/en/docs/manual/advanced/graphics-group)》.
Graphics Group (hereinafter referred to as Group) in G6 is similar to <a href='https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g' target='_blank'> `<g>` tag in SVG </a>: Group a container of a group of graphics. The transformations on a Group such as clipping, rotating, zooming, and translating will be applied to all the children of the Group. The properties like color and position will also be inherited by its children. Besides, Group can be nested for complicated objects. For more information about Group, please refer to [Graphics Group](/en/docs/manual/advanced/keyconcept/graphics-group) document.
## Instance Declaration
@ -21,10 +21,10 @@ Add a new group to the group.
**Parameters**
| Name | Type | Description |
| --- | --- | --- |
| param | Function / Object / undefined | |
| cfg | Object | |
| Name | Type |
| --- | --- |
| param | Function / Object / undefined |
| cfg | Object |
@ -39,14 +39,14 @@ group.addGroup({
### addShape(type, cfgs)
Add a new shape into the group<br />⚠️**Attention:** the clip and transform operations will affect all the shapes in the group. The graphics and their attributes are introduced in [Shape](/en/docs/api/Shape)。
Add a new shape into the group<br /><span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>Attention:</strong></span> the clip and transform operations will affect all the shapes in the group. The graphics and their properties are introduced in [Shape API](/en/docs/api/Shape)。
**Parameters**
| Name | Type | Description |
| --- | --- | --- |
| type | String | The type of the shape. Options: `'rect'`, `'circle'`, `'fan'`, `'ellipse'`, `'marker'`, `'image'`, and so on. Please refer to [Shape and Their Attributes](/en/docs/manual/advanced/shape-and-properties) |
| type | String | The type of the shape. Options: `'rect'`, `'circle'`, `'fan'`, `'ellipse'`, `'marker'`, `'image'`, and so on. Please refer to [Graphics Shape Properties](/en/docs/manual/advanced/keyconcept/shape-and-properties) document |
| cfg | Object | The configurations of the shape. |

View File

@ -3,7 +3,7 @@ title: Graphics Group
order: 8
---
图形分组 Graphics Group下文简称 Group 类似于 [SVG](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g) 中的 [`<g>`](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g) [标签](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g)Group 是用来组合图形对象的容器。在 Group 上添加变换例如剪裁、旋转、放缩、平移等会应用到其所有的子元素上。在 Group 上添加属性例如颜色、位置等会被其所有的子元素继承。此外 Group 可以多层嵌套使用,因此可以用来定义复杂的对象。关于 Group 更详细的介绍请参考《[图形分组 Group](/zh/docs/manual/advanced/graphics-group)》
图形分组 Graphics Group下文简称 Group 类似于 <a href='https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g' target='_blank'>SVG 中的 `<g>` 标签</a>Group 是用来组合图形对象的容器。在 Group 上添加变换例如剪裁、旋转、放缩、平移等会应用到其所有的子元素上。在 Group 上添加属性例如颜色、位置等会被其所有的子元素继承。此外 Group 可以多层嵌套使用,因此可以用来定义复杂的对象。关于 Group 更详细的介绍请参考 [图形分组 Group](/zh/docs/manual/advanced/keyconcept/graphics-group) 文档
## 声明实例
@ -21,10 +21,10 @@ const group = new Group(cfgs);
**参数**
| 名称 | 类型 | 说明 |
| --- | --- | --- |
| param | Function / Object / undefined | |
| cfg | Object | |
| 名称 | 类型 |
| --- | --- |
| param | Function / Object / undefined |
| cfg | Object |
@ -39,14 +39,14 @@ group.addGroup({
### addShape(type, cfgs)
向分组中添加新的图形。<br />**注意**:在分组上添加的 clip transform 等操作会影响到该分组中的所有图形。所有图形及其绘图属性请见 [Shape](/zh/docs/api/Shape)。
向分组中添加新的图形。<br /><span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>⚠️注意:</strong></span>:在分组上添加的 clip transform 等操作会影响到该分组中的所有图形。所有图形及其绘图属性请见 [Shape API](/zh/docs/api/Shape)。
**参数**
| 名称 | 类型 | 说明 |
| --- | --- | --- |
| type | String | 图元素类型,值可以为:`'rect'`、`'circle'`、`'fan'`、`'ellipse'`、`'marker'`、`'image'` 等,具体参考[Shape 的类型及属性](/zh/docs/manual/advanced/shape-and-properties) |
| type | String | 图元素类型,值可以为:`'rect'`、`'circle'`、`'fan'`、`'ellipse'`、`'marker'`、`'image'` 等,具体参考 [Shape 的类型及属性](/zh/docs/manual/advanced/keyconcept/shape-and-properties) 教程 |
| cfg | Object | 图元素的属性 |
@ -203,7 +203,7 @@ const child = childrens[childrens.length - 1]
### getChildByIndex(index
返回第 `index` 个子元素,从`0`开始计数。<br />返回值: Object
返回第 `index` 个子元素,从 `0` 开始计数。<br />返回值: Object
**参数**
@ -211,7 +211,7 @@ const child = childrens[childrens.length - 1]
| 名称 | 类型 | 说明 |
| --- | --- | --- |
| index | Number | 子元素的序号,默认为 0 |
| index | Number | 子元素的序号,默认为 `0` |

94
docs/api/Plugins.en.md Normal file
View File

@ -0,0 +1,94 @@
---
title: Plugins
order: 9
---
There are several plugins in G6 which can be used inside and ouside G6 freely.
- [Grid](#grid)
- [Minimap](#minimap)
- [Edge Bundling](#edge-bundling)
## Configure to Graph
In G6, Minimap is a plugin, which is packed as independent package. Here, we import Grid and Minimap for example:
```html
<body>
<!-- Import Grid by CDN -->
<script src="https://gw.alipayobjects.com/os/antv/pkg/_antv.g6-3.1.1/build/grid.js"></script>
<!-- Import Minimap by CDN -->
<script src="https://gw.alipayobjects.com/os/antv/pkg/_antv.g6-3.1.1/build/minimap.js"></script>
</body>
```
You only need to instantiate it and configure the minimap onto the instance of Graph:
```javascript
// Instantialize the Grid plugin
const grid = new Grid();
// Instantialize the Minimap plugin
const minimap = new Minimap();
const graph = new G6.Graph({
//... Other configurations
plugins: [ grid, minimap ] // Configure Grid and Minimap to the graph
});
```
## Grid
Grid draw grids on the canvas.
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*y8u6Rrc78uIAAAAAAAAAAABkARQnAQ' width=300 />
Grid has no configurations. Just use the code in [Configure to Graph](#configure-to-graph) to use it.
## Minimap
Minimap is a tool for quick preview and exploration on large graph.
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*v1svQLkEPrUAAAAAAAAAAABkARQnAQ' width=300 />
It can be configured to adjust the styles and functions.
### Configuration
| Name | Type | Description |
| --- | --- | --- |
| container | Object | The DOM container of Minimap. The plugin will generate a new one if `container` is not defined |
| className | String | The className of the DOM element of the Minimap |
| viewportClassName | String | The className of the DOM element of the view port on the Minimap |
| type | String | Render type. Options: `'default'`: Render all the graphics shapes on the graph; `'keyShape'`: Only render the keyShape of the items on the graph to reach better performance; `'delegate'`: Only render the delegate of the items on the graph to reach better performance. Performance: `'default'` < `'keyShape'` < `'delegate'`. `'default'` by default |
| size | Array | The size of the Minimap |
| delegateStyle | Object | Takes effect when `type` is `'delegate'`. The style of the delegate of the items on the graph |
The `delegateStyle` has the properties:
| Name | Type | Description |
| --- | --- | --- | --- |
| fill | String | Filling color |
| stroke | String | Stroke color |
| lineWidth | Number | The width of the stroke |
| opacity | Number | Opacity |
| fillOpacity | Number | Filling opacity |
## Edge Bundling
In complex graph with large number of edges, edge bundling can help you to improve the visual clutter.
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*z9iXQq_kcrYAAAAAAAAAAABkARQnAQ' width=600 />
> Edge bundling on American airline graph. <a href='http://antv-2018.alipay.com/zh-cn/g6/3.x/demo/case/american-migration-bundling.html' target='_blank'>Demo Link</a>. <a href='https://g6.antv.vision/zh/docs/manual/cases/edgeBundling' target='_blank'>Demo Document</a>.
The edge bundling plugin can be configured to adjust the styles and functions.
### Configuration
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| K | Number | 0.1 | The strength of the bundling |
| lambda | Number | 0.1 | The initial step length |
| divisions | Number | 1 | The initial number of division on each edge. It will be multipled by `divRate` in each cycle |
| divRate | Number | 2 | The rate of the divisions increasement. Large number means smoother result, but the performance will be worse when the number is too large |
| cycles | Number | 6 | The number of outer interations |
| iterations | Number | 90 | The initial number of inner interations. It will be multiplied by `iterRate` in each cycle |
| iterRate | Number | 0.6666667 | The rate of the iterations decreasement |
| bundleThreshold | Number | 0.6 | The edge similarity threshold for bundling. Large number means the edges in one bundle have smaller similarity, in other words, more edges in one bundle |

94
docs/api/Plugins.zh.md Normal file
View File

@ -0,0 +1,94 @@
---
title: 插件 Plugins
order: 9
---
G6 中支持插件提供了一些可插拔的组件,可自用使用在 G6 或其他应用当中。这些插件包括:
- [Grid](#grid)
- [Minimap](#minimap)
- [Edge Bundling](#edge-bundling)
## 配置方法
G6 的插件是独立的包,需要单独引入,以 Grid 和 Minimap 插件为例:
```html
<body>
<!-- 通过 CDN 引入 Grid -->
<script src="https://gw.alipayobjects.com/os/antv/pkg/_antv.g6-3.1.1/build/grid.js"></script>
<!-- 通过 CDN 引入 Minimap -->
<script src="https://gw.alipayobjects.com/os/antv/pkg/_antv.g6-3.1.1/build/minimap.js"></script>
</body>
```
引入后,首先实例化需要使用的某插件对象。然后,在实例化图时将其配置到 `plugins` 中:
```javascript
// 实例化 Grid 插件
const grid = new Grid();
const minimap = new Minimap();
const graph = new G6.Graph({
//... 其他配置项
plugins: [ grid, minimap ] // 配置 Grid 插件和 Minimap 插件
});
```
## Grid
Grid 插件在画布上绘制了网格。
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*y8u6Rrc78uIAAAAAAAAAAABkARQnAQ' width=300 />
Grid 没有配置项。使用 [配置方法](#配置方法) 中代码实例化即可。
## Minimap
Minimap 是用于快速预览和探索图的工具。
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*v1svQLkEPrUAAAAAAAAAAABkARQnAQ' width=300 />
实例化时可以通过配置项调整 Minimap 的样式和功能。
### 配置项
| 名称 | 类型 | 描述 |
| --- | --- | --- | --- |
| container | Object | 放置 Minimap 的 DOM 容器。若不指定则自动生成 |
| className | String | 生成的 DOM 元素的 className |
| viewportClassName | String | Minimap 上视窗 DOM 元素的 className |
| type | String | 选项:`'default'`:渲染图上所有图形;`'keyShape'`:只渲染图上元素的 keyShape以减少渲染成本`'delegate'`:只渲染图上元素的大致图形,以降低渲染成本。渲染成本 `'default'` > `'keyShape'` > `'delegate'`。默认为 `'default'` |
| size | Array | Minimap 的大小 |
| delegateStyle | Object | 在 `type``'delegate'` 时生效,代表元素大致图形的样式 |
其中delegateStyle 可以设置如下属性:
| 名称 | 类型 | 描述 |
| --- | --- | --- | --- |
| fill | String | 填充颜色 |
| stroke | String | 描边颜色 |
| lineWidth | Number | 描边宽度 |
| opacity | Number | 透明度 |
| fillOpacity | Number | 填充透明度 |
## Edge Bundling
在关系复杂、繁多的大规模图上,通过边绑定可以降低视觉复杂度。
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*z9iXQq_kcrYAAAAAAAAAAABkARQnAQ' width=600 />
> 美国航线图边绑定。<a href='http://antv-2018.alipay.com/zh-cn/g6/3.x/demo/case/american-migration-bundling.html' target='_blank'>Demo 链接</a>。该 <a href='https://g6.antv.vision/zh/docs/manual/cases/edgeBundling' target='_blank'>Demo 教程</a>
实例化时可以通过配置项调整边绑定的功能。
### 配置项
| 名称 | 类型 | 默认值 | 描述 |
| --- | --- | --- | --- |
| K | Number | 0.1 | 边绑定的强度 |
| lambda | Number | 0.1 | 算法的初始步长 |
| divisions | Number | 1 | 初始的切割点数,即每条边将会被切割成的份数。每次迭代将会被乘以 `divRate` |
| divRate | Number | 2 | 切割增长率,每次迭代都会乘以该数字。数字越大,绑定越平滑,但计算量将增大 |
| cycles | Number | 6 | 迭代次数 |
| iterations | Number | 90 | 初始的内迭代次数,每次外迭代中将会被乘以 `iterRate` |
| iterRate | Number | 0.6666667 | 迭代下降率 |
| bundleThreshold | Number | 0.6 | 判定边是否应该绑定在一起的相似容忍度,数值越大,被绑在一起的边相似度越低,数量越多 |

View File

@ -6,9 +6,12 @@ order: 7
This document shows the functions that should be implemented or rewrited when custom nodes by `G6.registerNode` or custom edges by `G6.registerEdge`.
## Usage
```
The following code is an example of customizing a type of edge:
```javascript
import G6 from '@antv/g6'
G6.registerNode('nodeName', {
G6.registerEdge('edgeName', {
labelPosition: 'center',
labelAutoRotate: true,
draw(cfg, group) {
// The other functions such as drawShape anddrawLabel can be called in draw(cfg, group)
this.drawShape()
@ -25,28 +28,25 @@ G6.registerNode('nodeName', {
update(cfg, item) {
// Update the item according
}
}, 'circle')
}, 'line')
```
## Attributes
### itemType
The type of the item. Options: `'node'`, `'edge'`.
## Properties
### labelPosition
The relative positions of label to the item. `'center'` by default.
- When `itemType` is `'node'`, options of `labelPosition` includes: `'top'`, `'bottom'`, `'left'`, `'right'` and `'center'`;
- When `itemType` is `'edge'`, options of `labelPosition` includes: `'start'`, `'end'` and `'center'`.
- When registering a type of node by `registerNode`, options of `labelPosition` includes: `'top'`, `'bottom'`, `'left'`, `'right'` and `'center'`;
- When registering a type of edge by `registerEdge`, options of `labelPosition` includes: `'start'`, `'end'` and `'center'`.
### labelAutoRotate
> Takes effect only when registerEdge.
> Takes effect only when `registerEdge`.
Whether rotate the label according to the edge. `false` by default.
Whether to rotate the label according to the edge. `false` by default.
**Tips: this is an unique attribute for edge.**
**Tips: this is an unique property for edge.**
## Draw
## Draw Functions
The parameters for the four functions about draw are the same. Please refer to `draw()`.
### draw(cfg, group)
@ -62,7 +62,7 @@ Draw the node or edge, including the label on the it. Return `keyShape` of it.
### afterDraw(cfg, group)
This function will be called after the node or edge being drawed. It is appropriate for extending graphics or animations for built-in node or edge.
## Update
## Update Functions
### update(cfg, item)
Update the node or edge, including the label on it.
@ -78,7 +78,7 @@ Update the node or edge, including the label on it.
This function will be called after the node or edge being updated.
### shouldUpdate(type)
Whether allow the node or edge to be updated.
Whether to allow the node or edge to be updated.
**Paramters**

View File

@ -5,12 +5,15 @@ order: 7
本文介绍的 Shape 相关方法是在自定义节点registerNode或自定义边registerEdge的过程中需要部分实现或复写的方法。
**友情提示:**以下属性和 API 方法,全部用于自定义节点和边时候使用,即作为 `G6.registerNode` / `G6.registerEdge` 的第二个参数中的方法使用
**友情提示:**以下属性和 API 方法,全部用于自定义节点和边时候使用,即作为 `G6.registerNode` / `G6.registerEdge` 的第二个参数中的方法。
## 用法
```
下面以注册边为例:
```javascript
import G6 from '@antv/g6'
G6.registerNode('nodeName', {
G6.registerEdge('edgeName', {
labelPosition: 'center',
labelAutoRotate: true,
draw(cfg, group) {
// 定义的其他方法都可以在draw里面调用 如 drawShape、drawLabel 等。
this.drawShape()
@ -28,28 +31,25 @@ G6.registerNode('nodeName', {
// 更新绘制的元素
}
}, 'circle')
}, 'line')
```
## 属性
### itemType
元素类型,目前支持 `'node'`、`'edge'`,后续可能会支持 `'group'`
### labelPosition
文本相对于图形的位置,默认值为 `'center'`
- 当 `itemType``'node'` 时,`labelPosition` 值包括:`'top'`、`'bottom'`、`'left'`、`'right'` 和 `'center'`
- 当 `itemType``'edge'` 时,`labelPosition` 值包括:`'start'`、`'end'` 和 `'center'`
- 当使用 `registerNode` 注册节点时,`labelPosition` 可选值包括:`'top'`、`'bottom'`、`'left'`、`'right'` 和 `'center'`
- 当使用 `registerEdge` 注册边时,`labelPosition` 可选值包括:`'start'`、`'end'` 和 `'center'`
### labelAutoRotate
> 只有在 registerEdge 时有用。
> 只有在 `registerEdge` 时有用。
文本是否跟着线自动旋转,默认值为 `false`
**提示edge特有。**
**提示edge 特有。**
## 绘制
## 绘制函数
绘制部分四个 API 的参数完全相同,参数说明部分参考 `draw()` 方法。
### draw(cfg, group)
@ -65,7 +65,7 @@ G6.registerNode('nodeName', {
### afterDraw(cfg, group)
绘制完成以后的操作,用户可继承现有的节点或边,在 `afterDraw()` 方法中扩展图形或添加动画。
## 更新
## 更新函数
### update(cfg, item)
更新节点或边,包括节点或边上的文本。

View File

@ -5,7 +5,7 @@ order: 2
If you are going to visualize a tree, TreeGraph of G6 is more appropriate than Graph. The main differences between `G6.TreeGraph` and `G6.Graph` are data structure and built-in layout algorithms:
- Data structure: In G6, the tree data has nested structure. Edges are implicit in it. Each node data has `id` and `children` attributes at least:
- Data structure: In G6, the tree data has nested structure. Edges are implicit in it. Each node data has `id` and `children` properties at least:
```javascript
const data = {
@ -24,7 +24,7 @@ const data = {
```
- Tree layout algorithms:
- Tree layout algorithms do not modify the source data. it generates a new data instead. And the source data will be an attribute of the new data. This mechanism will reduce the complexity of transformation from nested data to nodes and edges in graph.
- Tree layout algorithms do not modify the source data. it generates a new data instead. And the source data will be a property of the new data. This mechanism will reduce the complexity of transformation from nested data to nodes and edges in graph.
- The layout will be re-calculated after adding / deleting / expanding / collapsing nodes on the tree.
@ -36,8 +36,8 @@ const data = {
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| layout | Object | null | **V3.0.4 supports configurations for TreeGraph layout**. Before V3.0.4, the layout is formatted as a function. We recommend developers to use configurations now. |
| animate | Boolean | true | Whether activate animation for relayout. |
| layout | Object | null | *V3.0.4 supports configurations for TreeGraph layout*. Before V3.0.4, the layout is formatted as a function. We recommend developers to use configurations now. |
| animate | Boolean | true | Whether to activate animation for relayout. |
**Usage**
@ -83,7 +83,7 @@ There are four layout algorithms for tree in G6: dendrogram, compactBox, mindmap
| direction | String | LR | The direction of layout. Options: `'LR'` , `'RL'` , `'TB'` , `'BT'` , `'H'` , and `'V'`.<br />L: Left; R: right; T: top; B: bottom; H: horizontal; V: vertical. |
| getChildren | Function | | Return all the children nodes of the current node. |
⚠️**Attention:** When`type='indeted'`, `direction` can only be `'LR'`, `'RL'`, and `'H'`.
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>Attention:</strong></span> When`type='indeted'`, `direction` can only be `'LR'`, `'RL'`, and `'H'`.
### dendrogram
@ -109,7 +109,7 @@ Different results with different `direction` values.
| rankSep | Number | 200 | The separation between nodes in adjacent levels. |
| nodeSize | Number | 20 | The node size. |
| subTreeSep | Number | 10 | The separation between sub trees. |
| isHorizontal | Boolean | true | Whether layout the tree in horizontal. |
| isHorizontal | Boolean | true | Whether to layout the tree in horizontal. |
### compactBox
@ -137,7 +137,7 @@ Different effects for different `direction` values.
| getVGap | Function | 18 | Set the vertical separations between nodes. |
| getHGap | Function | 18 | Set the horizontal separations between nodes. |
⚠️**Attention:** `getWidth`, `getHeight`, `getVGap`, and `getHGap` will not change the node size:
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>Attention:</strong></span> `getWidth`, `getHeight`, `getVGap`, and `getHGap` will not change the node size:
```javascript
/*
* Gaps: filling space between nodes
@ -240,7 +240,7 @@ Incrementally update the children data of the parent.
| data | Object | true | The data of subtreee. |
| parent | Node | String | false | The id or instance of parent node. |
⚠️**Attention:** When the `parent` is null, this operation will update the graph fully.
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>Attention:</strong></span> When the `parent` is null, this operation will update the graph fully.
**Usage**
@ -316,7 +316,7 @@ Refresh the layout. Usually, it is called after changing data.
| Name | Type | Required| Description |
| --- | --- | --- | --- |
| fitView | Boolean | false | Whether fit view after refreshing layout. |
| fitView | Boolean | false | Whether to fit view after refreshing layout. |
**Usage**

View File

@ -35,8 +35,8 @@ const data = {
**参数**
| 名称 | 类型 | 默认值 | 描述 |
| --- | --- | --- | --- |
| layout | Object | null | **3.0.4 版本开始支持树布局算法配置**3.0.4 版本之前是 function 形式。建议开发者使用配置形式,操作粒度更细。 |
| --- | --- | ----- | --- |
| layout | Object | null | *V3.0.4 版本开始支持树布局算法配置*。V3.0.4 版本之前是 function 形式。建议开发者使用配置形式,操作粒度更细。 |
| animate | Boolean | true | 默认打开重布局动画开关。 |
@ -71,7 +71,7 @@ const treeGraph = new G6.TreeGraph({
```
## layout配置项
## layout 配置项
layout 目前支持 dendrogram、compactBox、mindmap 和 indeted 四种布局方式。
@ -83,7 +83,7 @@ layout 目前支持 dendrogram、compactBox、mindmap 和 indeted 四种布局
| direction | String | LR | 布局方向,有 `LR` , `RL` , `TB` , `BT` , `H` , `V` 可选。<br />LRTBH垂直V水平。 |
| getChildren | Function | | 返回当前节点的所有子节点 |
⚠️**注意:**`type='indeted'` 时,`direction` 只能取 LR、RL 和 H 这三个值。
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>⚠️注意:</strong></span>`type='indeted'` 时,`direction` 只能取 `'LR'``'RL'``'H'` 这三个值。
### dendrogram
@ -94,11 +94,11 @@ layout 目前支持 dendrogram、compactBox、mindmap 和 indeted 四种布局
| LR | RL | H |
| --- | --- | --- |
| <img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*zX7tSLqBvwcAAAAAAAAAAABkARQnAQ' width='230' height='100'> | <img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*qVbeR4oq4lYAAAAAAAAAAABkARQnAQ' width='230' height='100'> | <img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*OHetRqedHOkAAAAAAAAAAABkARQnAQ' width='230' height='100'> |
| <img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*zX7tSLqBvwcAAAAAAAAAAABkARQnAQ' width='180' height='100'> | <img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*qVbeR4oq4lYAAAAAAAAAAABkARQnAQ' width='180' height='100'> | <img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*OHetRqedHOkAAAAAAAAAAABkARQnAQ' width='250' height='100'> |
| TB | BT | V |
| --- | --- | --- |
| <img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*P_OETZsj17cAAAAAAAAAAABkARQnAQ' width='230' height='100'> | <img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*n6sFS57g424AAAAAAAAAAABkARQnAQ' width='230' height='100'> | <img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*CyVbQ5q_0_cAAAAAAAAAAABkARQnAQ' width='230' height='100'> |
| <img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*P_OETZsj17cAAAAAAAAAAABkARQnAQ' width='100' height='150'> | <img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*n6sFS57g424AAAAAAAAAAABkARQnAQ' width='100' height='150'> | <img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*CyVbQ5q_0_cAAAAAAAAAAABkARQnAQ' width='100' height='180'> |
**dendrogram 配置项**
@ -137,7 +137,7 @@ layout 目前支持 dendrogram、compactBox、mindmap 和 indeted 四种布局
| getVGap | Function | 18 | 指定节点之间的垂直间距 |
| getHGap | Function | 18 | 指定节点之间的水平间距 |
⚠️**注意:**使用 `getWidth`、`getHeight`、`getVGap` 和 `getHGap` 指定节点的宽高及间距后,并不会改变节点的大小,具体原理如下所示:
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>⚠️注意:</strong></span>使用 `getWidth`、`getHeight`、`getVGap` 和 `getHGap` 指定节点的宽高及间距后,并不会改变节点的大小,具体原理如下所示:
```javascript
/*
* Gaps: filling space between nodes
@ -165,7 +165,7 @@ layout 目前支持 dendrogram、compactBox、mindmap 和 indeted 四种布局
| LR | RL | H |
| --- | --- | --- |
| <img src='https://intranetproxy.alipay.com/skylark/lark/0/2019/png/178530/1560910055783-3783faed-29f0-4e34-9076-df951aa6ea10.png#align=left&display=inline&percent=0&size=0&status=done' width='230' height='100'> | <img src='https://intranetproxy.alipay.com/skylark/lark/0/2019/png/178530/1560910055615-54aaca32-7de4-471e-8600-611854094b90.png#align=left&display=inline&percent=0&size=0&status=done' width='230' height='100'> | <img src='https://intranetproxy.alipay.com/skylark/lark/0/2019/png/178530/1560910055676-86d316d8-9487-4b3d-99a4-27b4a8c091c0.png#align=left&display=inline&percent=0&size=0&status=done' width='230' height='100'> |
| <img src='https://intranetproxy.alipay.com/skylark/lark/0/2019/png/178530/1560910055783-3783faed-29f0-4e34-9076-df951aa6ea10.png#align=left&display=inline&percent=0&size=0&status=done' width='150' height='100'> | <img src='https://intranetproxy.alipay.com/skylark/lark/0/2019/png/178530/1560910055615-54aaca32-7de4-471e-8600-611854094b90.png#align=left&display=inline&percent=0&size=0&status=done' width='150' height='100'> | <img src='https://intranetproxy.alipay.com/skylark/lark/0/2019/png/178530/1560910055676-86d316d8-9487-4b3d-99a4-27b4a8c091c0.png#align=left&display=inline&percent=0&size=0&status=done' width='230' height='100'> |
**indented配置项**
@ -181,7 +181,7 @@ layout 目前支持 dendrogram、compactBox、mindmap 和 indeted 四种布局
**mindmap示意图**
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*J1l5RofvbP0AAAAAAAAAAABkARQnAQ' width='750'>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*J1l5RofvbP0AAAAAAAAAAABkARQnAQ' width='350'>
**mindmap配置项**
@ -240,7 +240,7 @@ treeGraph.addChild(data, 'root')
| data | Object | true | 子树的数据 |
| parent | Node | String | false | 父节点或父节点 ID |
⚠️**注意:**当parent参数为空时,则全量更新。
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>⚠️注意:</strong></span>`parent` 参数为空时,则全量更新。
**用法**

View File

@ -4,7 +4,7 @@ order: 1
---
## Random
Random is the default layout in G6. It will take effect when `layout` is not configured on the Graph instance and there is no position information in node data.
Random is the default layout in G6. It will take effect when `layout` is not assigned to the Graph instance and there is no position information in node data.
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*G5_uRodUTaYAAAAAAAAAAABkARQnAQ' width=430 />
@ -18,6 +18,9 @@ Random is the default layout in G6. It will take effect when `layout` is not con
#### height
**Type**: Number<br />**Default**: The height of the graph<br />**Required**: false<br />**Description**: The height of the layout
#### workerEnabled
**Type**: Boolean<br />**Default**: false<br />**Required**: false<br />**Description**: Whether to enable the web-worker in case layout calculation takes too long to block page interaction
### Function
The same as the superclass Layout, users do not need to concern about the function calling, which will be controlled by G6.
@ -33,7 +36,7 @@ const graph = new G6.Graph({
width: 300,
height: 300
}
);
});
```
## MDS
@ -48,6 +51,9 @@ MDS (Multidimensional scaling) is used for project high dimensional data onto l
#### linkDistance
**Type**: Number<br />**Default**: 50<br />**Required**: false<br />**Description**: The edge length
#### workerEnabled
**Type**: Boolean<br />**Default**: false<br />**Required**: false<br />**Description**: Whether to enable the web-worker in case layout calculation takes too long to block page interaction
### Function
The same as the superclass Layout, users do not need to concern about the function calling, which will be controlled by G6.
@ -59,9 +65,10 @@ const graph = new G6.Graph({
width: 1000,
height: 600,
layout: {
type: 'mds'
type: 'mds',
workerEnabled: true // Whether to activate web-worker
}
);
});
```
## Force
@ -81,13 +88,16 @@ Force is the classical force-dicrected layout algorithm, which corresponds to fo
#### nodeStrength
**Type**: Number<br />**Default**: null<br />**Required**: false<br />**Description**: The strength of node force. Positive value means attractive force, negative value means repulsive force.
**Type**: Number<br />**Default**: null<br />**Required**: false<br />**Description**: The strength of node force. Positive value means attractive force, negative value means repulsive force
#### edgeStrength
**Type**: Number<br />**Default**: null<br />**Required**: false<br />**Description**: The strength of edge force. Calculated according to the degree of nodes by default
#### preventOverlap
**Type**: Number<br />**Default**: false<br />**Required**: false<br />**Description**: Whether to prevent node overlappings. To activate preventing node overlappings, `nodeSize` is required, which is used for collide detection. The size in the node data will take effect if `nodeSize` is not assigned.
#### collideStrength
**Type**: Number<br />**Default**: 1<br />**Required**: false<br />**Description**: The strength of force for preventing node overlappings. The range is [0, 1]
@ -95,13 +105,32 @@ Force is the classical force-dicrected layout algorithm, which corresponds to fo
#### nodeSize
**Type**: Number<br />**Default**: 10<br />**Required**: false<br />**Description**: The diameter of the node. It is used for preventing node overlappings. If `nodeSize` is not assigned, the size property in node data will take effect. If the size in node data does not exist either, `nodeSize` is assigned to 10 by default
#### nodeSpacing
**Type**: Number / Function
<br />**Default**: 0
<br />**Required**: false
<br />**Example**: Example 1: 10
<br />Example 2:  
```javascript
d => {
  // d is a node
  if (d.id === 'node1') {
    return 100;
  }
  return 10;
}
```
<br />**Description**:
Takes effect when `preventOverlap` is `true`. It is the minimum distance between nodes to prevent node overlappings. It can be a function to define different distances for different nodes (example 2)
#### alpha
**Type**: Number<br />**Default**: 0.3<br />**Required**: false<br />**Description**: The current alpha of convergence
#### alphaDecay
**Type**: Number<br />**Default**: 0.028<br />**Required**: false<br />**Description**: The decay ratio of alpha for convergence. THe range is [0, 1]. 0.028 corresponds to 300 times iteration
**Type**: Number<br />**Default**: 0.028<br />**Required**: false<br />**Description**: The decay ratio of alpha for convergence. The range is [0, 1]. 0.028 corresponds to 300 iterations
#### alphaMin
@ -120,6 +149,10 @@ Force is the classical force-dicrected layout algorithm, which corresponds to fo
**Type**: Function<br />**Default**: {}<br />**Required**: false<br />**Description**: The callback function after layout
#### workerEnabled
**Type**: Boolean<br />**Default**: false<br />**Required**: false<br />**Description**: Whether to enable the web-worker in case layout calculation takes too long to block page interaction
### Function
The same as the superclass Layout, users do not need to concern about the function calling, which will be controlled by G6.
@ -150,12 +183,13 @@ const graph = new G6.Graph({
console.log('force layout done');
}
}
);
});
```
## Fruchterman
Fruchterman is a kind of force-directed layout. G6 implements it according to the paper[Graph Drawing by Force-directed Placement](http://www.mathe2.uni-bayreuth.de/axel/papers/reingold:graph_drawing_by_force_directed_placement.pdf).
Fruchterman is a kind of force-directed layout. G6 implements it according to the paper
<a href='http://www.mathe2.uni-bayreuth.de/axel/papers/reingold:graph_drawing_by_force_directed_placement.pdf' target='_blank'>Graph Drawing by Force-directed Placement</a>.
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*jK3ITYqVJnQAAAAAAAAAAABkARQnAQ' width=600 />
@ -178,13 +212,17 @@ Fruchterman is a kind of force-directed layout. G6 implements it according to th
#### clustering
**Type**: Boolean<br />**Default**: false<br />**Required**: false<br />**Description**: Whether layout by cluster
**Type**: Boolean<br />**Default**: false<br />**Required**: false<br />**Description**: Whether to layout by cluster
#### clusterGravity
**Type**: Number<br />**Default**: 10<br />**Required**: false<br />**Description**: The gravity of each cluster, which will affect the compactness of each cluster. Takes effect only when `clustering` is `true`
#### workerEnabled
**Type**: Boolean<br />**Default**: false<br />**Required**: false<br />**Description**: Whether to enable the web-worker in case layout calculation takes too long to block page interaction
### Function
The same as the superclass Layout, users do not need to concern about the function calling, which will be controlled by G6.
@ -203,14 +241,18 @@ const graph = new G6.Graph({
speed: 2,
clustering: true,
clusterGravity: 30,
maxIteration: 2000
maxIteration: 2000,
workerEnabled: true // Whether to activate web-worker
}
);
});
```
## Circular
Circular layout arranges the node on a circle. By tuning the configurations, user can adjust the node ordering method, division number, radial layout, and so on. G6 implements it according to the paper: [A framework and algorithms for circular drawings of graphs](https://www.sciencedirect.com/science/article/pii/S1570866705000031). <br />
Circular layout arranges the node on a circle. By tuning the configurations, user can adjust the node ordering method, division number, radial layout, and so on. G6 implements it according to the paper:
<a href='https://www.sciencedirect.com/science/article/pii/S1570866705000031' target='_blank'>A framework and algorithms for circular drawings of graphs</a>.
<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-3idTK1xa6wAAAAAAAAAAABkARQnAQ' width=270 />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*_nLORItzM5QAAAAAAAAAAABkARQnAQ' width=270 />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*6J6BRIjmXKAAAAAAAAAAAABkARQnAQ' width=270 />
@ -235,7 +277,7 @@ Circular layout arranges the node on a circle. By tuning the configurations, use
#### clockwise
**Type**: Boolean<br />**Default**: true<br />**Required**: false<br />**Description**: Whether layout clockwisely
**Type**: Boolean<br />**Default**: true<br />**Required**: false<br />**Description**: Whether to layout clockwisely
#### divisions
@ -249,6 +291,11 @@ Circular layout arranges the node on a circle. By tuning the configurations, use
#### angleRatio
**Type**: Number<br />**Default**: 1<br />**Required**: false<br />**Description**: How many 2*PIs Between the first node and the last node
#### workerEnabled
**Type**: Boolean<br />**Default**: false<br />**Required**: false<br />**Description**: Whether to enable the web-worker in case layout calculation takes too long to block page interaction
### Function
The same as the superclass Layout, users do not need to concern about the function calling, which will be controlled by G6.
@ -271,27 +318,28 @@ const graph = new G6.Graph({
ordering: 'degree',
angleRatio: 1
}
);
});
```
## Radial
Radial layout arranges the nodes to concentrics centered at a focus node according to their shortest path length to the focus node. G6 implements it according to the paper: [More Flexible Radial Layout](http://emis.ams.org/journals/JGAA/accepted/2011/BrandesPich2011.15.1.pdf).
Radial layout arranges the nodes to concentrics centered at a focus node according to their shortest path length to the focus node. G6 implements it according to the paper:
<a href='http://emis.ams.org/journals/JGAA/accepted/2011/BrandesPich2011.15.1.pdf' target='_blank'>More Flexible Radial Layout</a>.
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GAFjRJeAoAsAAAAAAAAAAABkARQnAQ' width=600 />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GAFjRJeAoAsAAAAAAAAAAABkARQnAQ' width=450 />
### Configuration
#### center
**Type**: Array<br />**Example**: [ 0, 0 ]<br />**Default**: The center of the graph<br />**Required**: false<br />**Description**: The center of the layout
**Type**: Array<br />**Example**: [ 0, 0 ]<br />**Default**: The center of the graph<br />**Required**: false<br />**Description**: The center of the layout.
#### linkDistance
**Type**: Number<br />**Default**: 50<br />**Required**: false<br />**Description**: The edge length
**Type**: Number<br />**Default**: 50<br />**Required**: false<br />**Description**: The edge length.
#### maxIteration
**Type**: Number<br />**Default**: 1000<br />**Required**: false<br />**Description**: The max iteration number
**Type**: Number<br />**Default**: 1000<br />**Required**: false<br />**Description**: The max iteration number.
#### focusNode
@ -303,19 +351,40 @@ Radial layout arranges the nodes to concentrics centered at a focus node accordi
#### preventOverlap
**Type**: Boolean<br />**Default**: false<br />**Required**: false<br />**Description**: Whether prevent node overlappings. To activate preventing node overlappings, [`nodeSize`](#xWjHN) is required, which is used for collide detection. The size in the node data will take effect if `nodeSize` is not assigned.
**Type**: Boolean<br />**Default**: false<br />**Required**: false<br />**Description**: Whether to prevent node overlappings. To activate preventing node overlappings, `nodeSize` is required, which is used for collide detection. The size in the node data will take effect if `nodeSize` is not assigned.
#### nodeSize
**Type**: Number<br />**Default**: 10<br />**Required**: false<br />**Description**: The diameter of the node. It is used for preventing node overlappings
#### nodeSpacing
**Type**: Number / Function
<br />**Default**: 0
<br />**Required**: false
<br />**Example**: Example 1: 10
<br />Example 2:  
```javascript
d => {
  // d is a node
  if (d.id === 'node1') {
    return 100;
  }
  return 10;
}
```
<br />**Description**:
Takes effect when `preventOverlap` is `true`. It is the minimum distance between nodes to prevent node overlappings. It can be a function to define different distances for different nodes (example 2)
#### maxPreventOverlapIteration
**Type**: Number<br />**Default**: 200<br />**Required**: false<br />**Description**: The maximum iteration number of preventing node overlappings
#### strictRadial
**Type**: Boolean<br />**Default**: true<br />**Required**: false<br />**Description**: Whether layout the graph as strict radial, which means the nodes will be arranged on each circle strictly. Takes effect only when `preventOverlap` is `true`
**Type**: Boolean<br />**Default**: true<br />**Required**: false<br />**Description**: Whether to layout the graph as strict radial, which means the nodes will be arranged on each circle strictly. Takes effect only when `preventOverlap` is `true`
- When `preventOverlap` is `true`, and `strictRadial` is `false`, the overlapped nodes are arranged along their circles strictly. But for the situation that there are too many nodes on a circle to be arranged, the overlappings might not be eliminated completely
- When `preventOverlap` is `true`, and `strictRadial` is `true` , the overlapped nodes can be arranged around their circle with small offsets.
@ -328,6 +397,19 @@ Radial layout arranges the nodes to concentrics centered at a focus node accordi
#### sortBy
**Type**: String<br />**Default**: undefined<br />**Required**: false<br />**Description**: Sort the nodes of the same level. `undefined` by default, which means place the nodes with connections as close as possible; `'data'` means place the node according to the ordering in data, the closer the nodes in data ordering, the closer the nodes will be placed. `sortBy` also can be assigned to any name of property in nodes data, such as `'cluster'`, `'name'` and so on (make sure the property exists in the data)
#### sortStrength
**Type**: Number<br />**Default**: 10<br />**Required**: false<br />**Description**: The strength to sort the nodes in the same circle. Larger number means place the nodes with smaller distance of `sortBy` more closely. Takes effect only when `sortBy` is not `undefined`
#### workerEnabled
**Type**: Boolean<br />**Default**: false<br />**Required**: false<br />**Description**: Whether to enable the web-worker in case layout calculation takes too long to block page interaction
### Function
The same as the superclass Layout, users do not need to concern about the function calling, which will be controlled by G6.
@ -340,7 +422,7 @@ const graph = new G6.Graph({
width: 1000,
height: 600,
layout: {
type: 'circular',
type: 'radial',
center: [ 200, 200 ], // The center of the graph by default
linkDistance: 50, // The edge length
maxIteration: 1000,
@ -348,9 +430,10 @@ const graph = new G6.Graph({
unitRadius: 100,
preventOverlap: true, // nodeSize or size in data is required for preventOverlap: true
nodeSize: 30,
strictRadial: false
strictRadial: false,
workerEnabled: true // Whether to activate web-worker
}
);
});
```
## Dagre
@ -362,7 +445,7 @@ Dagre is an hierarchical layout.
### Configuration
#### rankdir
**Type**: String<br />**Options**: 'TB' | 'BT' | 'LR' | 'RL'<br />**Default**: 'TB'<br />**Required**: false<br />**Description**: 布局的方向. T:top; B:bottom; L:left; R:right.
**Type**: String<br />**Options**: 'TB' | 'BT' | 'LR' | 'RL'<br />**Default**: 'TB'<br />**Required**: false<br />**Description**: The layout direction. T:top; B:bottom; L:left; R:right.
- 'TB':Layout the graph from the top to the bottom;
- 'BT':Layout the graph from the bottom to the top;
@ -373,12 +456,12 @@ Dagre is an hierarchical layout.
#### align
**Type**: String<br />**Options**: 'UL' | 'UR' | 'DL' | 'DR'<br />**Default**: 'UL'<br />**Required**: false<br />**Description**: 节点对齐方式. U:upper; D:down; L:left; R:right
**Type**: String<br />**Options**: 'UL' | 'UR' | 'DL' | 'DR'<br />**Default**: 'UL'<br />**Required**: false<br />**Description**: The alignment of the nodes. U: upper; D: down; L: left; R: right
- 'UL':对齐到左上角;
- 'UR':对齐到右上角;
- 'DL':对齐到左下角;
- 'DR':对齐到右下角.
- 'UL': aligns the nodes to the upper left;
- 'UR': aligns the nodes to the upper right;
- 'DL': aligns the nodes to the down left;
- 'DR': aligns the nodes to the upper right.
#### nodesep
@ -414,7 +497,11 @@ Dagre is an hierarchical layout.
#### controlPoints
**Type**: Boolean<br />**Default**: true<br />**Required**: false<br />**Description**: Whether keep the control points of layout
**Type**: Boolean<br />**Default**: true<br />**Required**: false<br />**Description**: Whether to keep the control points of layout
#### workerEnabled
**Type**: Boolean<br />**Default**: false<br />**Required**: false<br />**Description**: Whether to enable the web-worker in case layout calculation takes too long to block page interaction
### Function
@ -436,12 +523,12 @@ const graph = new G6.Graph({
ranksep: 50,
controlPoints: true
}
);
});
```
## Concentric
Concentric arranges the nodes on several concentrics. By tuning the parameters, users could order the nodes according to some property of node data, degree by default. Larger the value, more center the node will be placed.
Concentric arranges the nodes on several concentric circles. By tuning the parameters, users could order the nodes according to some property of node data, degree by default. Larger the value, more center the node will be placed.
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*QpyPTbBpO2AAAAAAAAAAAABkARQnAQ' width=600 />
@ -453,7 +540,7 @@ Concentric arranges the nodes on several concentrics. By tuning the parameters,
#### preventOverlap
**Type**: Boolean<br />**Default**: false<br />**Required**: false<br />**Description**: Whether prevent node overalappings. To activate this ability, [`nodeSize`](https://www.yuque.com/antv/g6/ngp0vg#xWjHN) should be assigned, which will be used for collide detection
**Type**: Boolean<br />**Default**: false<br />**Required**: false<br />**Description**: Whether to prevent node overlappings. To activate preventing node overlappings, `nodeSize` is required, which is used for collide detection. The size in the node data will take effect if `nodeSize` is not assigned. If the size in node data does not exist either, `nodeSize` is assigned to 30 by default
#### nodeSize
@ -481,13 +568,17 @@ Concentric arranges the nodes on several concentrics. By tuning the parameters,
#### maxLevelDiff
**Type**: Number<br />**默认值:**undefined<br />**Required**: false<br />**Description**: The sum of concentric values in each level. If it is undefined, maxValue / 4 will take place, where maxValue is the max value of ordering properties. For example, if sortBy='degree', maxValue is the max degree value of all the nodes
**Type**: Number<br />**默认值:**undefined<br />**Required**: false<br />**Description**: The sum of concentric values in each level. If it is undefined, maxValue / 4 will take place, where maxValue is the max value of ordering properties. For example, if `sortBy` is `'degree'`, maxValue is the max degree value of all the nodes
#### sortBy
**Type**: String<br />**Default**: undefined<br />**Required**: false<br />**Description**: Order the nodes according to this parameter. It is the property's name of node. The node with higher value will be placed to the center. If it is undefined, the algorithm will order the nodes by their degree
#### workerEnabled
**Type**: Boolean<br />**Default**: false<br />**Required**: false<br />**Description**: Whether to enable the web-worker in case layout calculation takes too long to block page interaction
### Function
The same as the superclass Layout, users do not need to concern about the function calling, which will be controlled by G6.
@ -510,16 +601,17 @@ const graph = new G6.Graph({
startAngle: 0,
clockwise: false,
maxLevelDiff: 10,
sortBy: 'degree'
sortBy: 'degree',
workerEnabled: true // Whether to activate web-worker
}
);
});
```
## Grid
Grid orders the nodes according to the configurations and arranged them onto grid.
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Oh6mRLVEBBIAAAAAAAAAAABkARQnAQ' width=850 />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Oh6mRLVEBBIAAAAAAAAAAABkARQnAQ' width=650 />
### Configuration
@ -528,7 +620,7 @@ Grid orders the nodes according to the configurations and arranged them onto gri
#### preventOverlap
**Type**: Boolean<br />**Default**: false<br />**Required**: false<br />**Description**: Prevent node overlappings. Only when the `nodeSize` is assigned, the collide detection will take effect
**Type**: Boolean<br />**Default**: false<br />**Required**: false<br />**Description**: Whether to prevent node overlappings. To activate preventing node overlappings, `nodeSize` is required, which is used for collide detection. The size in the node data will take effect if `nodeSize` is not assigned. If the size in node data does not exist either, `nodeSize` is assigned to 30 by default
#### nodeSize
@ -555,6 +647,10 @@ Grid orders the nodes according to the configurations and arranged them onto gri
**Type**: String<br />**Default**: undefined<br />**Required**: false<br />**Description**: The ordering method for nodes. Smaller the index in the ordered array, more center the node will be placed. If `sortBy` is undefined, the algorithm order the nodes according to their degrees
#### workerEnabled
**Type**: Boolean<br />**Default**: false<br />**Required**: false<br />**Description**: Whether to enable the web-worker in case layout calculation takes too long to block page interaction
### Function
The same as the superclass Layout, users do not need to concern about the function calling, which will be controlled by G6.
@ -567,7 +663,7 @@ const graph = new G6.Graph({
width: 1000,
height: 600,
layout: {
type: 'concentric',
type: 'grid',
begin: [ 0, 0 ],
preventOverlap: true, // nodeSize or size in data is required for preventOverlap: true
preventOverlapPdding: 20,
@ -577,5 +673,5 @@ const graph = new G6.Graph({
cols: 5,
sortBy: 'degree'
}
);
});
```

View File

@ -18,6 +18,10 @@ Random 布局是 G6 中的默认布局方法。当实例化图时没有指定布
#### height
**类型** Number<br />**默认值**:图的高度<br />**是否必须**false<br />**说明**:布局的高度范围
#### workerEnabled
**类型**: Boolean<br />**默认值**: false<br />**是否必须**: false<br />**说明**: 是否启用 web-worker 以防布局计算时间过长阻塞页面交互
### 方法
与父类 Layout 的方法相同。使用该布局时不需要关心内部方法的调用,由 G6 控制。
@ -33,12 +37,12 @@ const graph = new G6.Graph({
width: 300,
height: 300
}
);
});
```
## MDS
MDS 布局是高维数据降维算法布局该算法全称 Multidimensional scaling <br />
MDS 布局是高维数据降维算法布局该算法全称 Multidimensional Scaling <br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*aUS7TJR2NHcAAAAAAAAAAABkARQnAQ' width=600 />
### 属性
@ -48,6 +52,10 @@ MDS 布局是高维数据降维算法布局该算法全称 Multidimensional
#### linkDistance
**类型** Number<br />**默认值**50<br />**是否必须**false<br />**说明**:边长度
#### workerEnabled
**类型**: Boolean<br />**默认值**: false<br />**是否必须**: false<br />**说明**: 是否启用 web-worker 以防布局计算时间过长阻塞页面交互
### 方法
与父类 Layout 的方法相同。使用该布局时不需要关心内部方法的调用,由 G6 控制。
@ -59,14 +67,15 @@ const graph = new G6.Graph({
width: 1000,
height: 600,
layout: {
type: 'mds'
type: 'mds',
workerEnabled: true // 可选,开启 web-worker
}
);
});
```
## Force
Force 布局经典的力导向布局方法,与 d3 的力导向布局方法相对应。其属性也与 d3 的力道布局参数相对应。
Force 布局经典的力导向布局方法,与 d3 的力导向布局方法相对应。其属性也与 d3.js 的力导布局参数相对应。
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Nt45Q6nnK2wAAAAAAAAAAABkARQnAQ' width=600 />
@ -88,20 +97,41 @@ Force 布局经典的力导向布局方法,与 d3 的力导向布局方法相
**类型**Number<br />**默认值**null<br />**是否必须**false<br />**说明**:边的作用力,默认根据节点的出入度自适应
#### preventOverlap
**类型**Number<br />**默认值**false<br />**是否必须**false<br />**说明**:是否防止重叠,必须配合下面属性 `nodeSize`,只有设置了与当前图节点大小相同的 `nodeSize` 值,才能够进行节点重叠的碰撞检测
#### collideStrength
**类型**Number<br />**默认值**1<br />**是否必须**false<br />**说明**:防止重叠的力强度,范围 [0, 1]
#### nodeSize
**类型** Number<br />**默认值**10<br />**是否必须**false<br />**说明**:节点大小(直径)。用于碰撞检测。若不指定,则根据传入的节点的 size 属性计算。若即不指定,即节点中也没有 `size`,则默认大小为 10
**类型** Number<br />**默认值**10<br />**是否必须**false<br />**说明**:节点大小(直径)。用于碰撞检测。若不指定,则根据传入的节点的 size 属性计算。若即不指定,即节点中也没有 `size`,则默认大小为 `10`
#### nodeSpacing
**类型**: Number / Function<br />**默认值**: 0<br />**是否必须**: false
<br />**示例**: Example 1: 10
<br />Example 2:  
```javascript
d => {
  // d is a node
  if (d.id === 'node1') {
    return 100;
  }
  return 10;
}
```
<br />**描述**:
`preventOverlap``true` 时生效, 防止重叠时节点边缘间距的最小值。可以是回调函数, 为不同节点设置不同的最小间距, 如示例 2 所示
#### alpha
**类型**Number<br />**默认值**0.3<br />**是否必须**false<br />**说明**:当前的迭代收敛阈值
#### alphaDecay
**类型**Number<br />**默认值**0.028<br />**是否必须**false<br />**说明**:迭代阈值的衰减率。[0, 1]0.028 对应迭代书为 300
**类型**Number<br />**默认值**0.028<br />**是否必须**false<br />**说明**:迭代阈值的衰减率。范围 [0, 1]。0.028 对应迭代数为 300
#### alphaMin
@ -109,7 +139,7 @@ Force 布局经典的力导向布局方法,与 d3 的力导向布局方法相
#### forceSimulation
**类型**Object<br />**默认值**null<br />**是否必须**false<br />**说明**:自定义 force 方法,若不指定,则使用 d3 的方法
**类型**Object<br />**默认值**null<br />**是否必须**false<br />**说明**:自定义 force 方法,若不指定,则使用 d3.js 的方法
#### onTick
@ -119,6 +149,9 @@ Force 布局经典的力导向布局方法,与 d3 的力导向布局方法相
#### onLayoutEnd
**类型**Function<br />**默认值**{}<br />**是否必须**false<br />**说明**:布局完成后的回调函数
#### workerEnabled
**类型**: Boolean<br />**默认值**: false<br />**是否必须**: false<br />**说明**: 是否启用 web-worker 以防布局计算时间过长阻塞页面交互
### 方法
与父类 Layout 的方法相同。使用该布局时不需要关心内部方法的调用,由 G6 控制。
@ -155,7 +188,8 @@ const graph = new G6.Graph({
## Fruchterman
Fruchterman 布局是一种力导布局。算法原文:[Graph Drawing by Force-directed Placement](http://www.mathe2.uni-bayreuth.de/axel/papers/reingold:graph_drawing_by_force_directed_placement.pdf)。
Fruchterman 布局是一种力导布局。算法原文:
<a href='http://www.mathe2.uni-bayreuth.de/axel/papers/reingold:graph_drawing_by_force_directed_placement.pdf' target='_blank'>Graph Drawing by Force-directed Placement</a>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*jK3ITYqVJnQAAAAAAAAAAABkARQnAQ' width=600 />
@ -184,6 +218,9 @@ Fruchterman 布局是一种力导布局。算法原文:[Graph Drawing by Force
#### clusterGravity
**类型** Number<br />**默认值**10<br />**是否必须**false<br />**说明**:聚类内部的重力大小,影响聚类的紧凑程度,在 `clustering``true` 时生效
#### workerEnabled
**类型**: Boolean<br />**默认值**: false<br />**是否必须**: false<br />**说明**: 是否启用 web-worker 以防布局计算时间过长阻塞页面交互
### 方法
与父类 Layout 的方法相同。使用该布局时不需要关心内部方法的调用,由 G6 控制。
@ -203,14 +240,17 @@ const graph = new G6.Graph({
speed: 2, // 可选
clustering: true, // 可选
clusterGravity: 30, // 可选
maxIteration: 2000
}
);
maxIteration: 2000, // 可选,迭代次数
workerEnabled: true // 可选,开启 web-worker }
});
```
## Circular
Circular 布局将所有节点布局在一个圆环上,可以选择节点在圆环上的排列顺序。可以通过参数的配置扩展出环的分组布局、螺旋形布局等。原文链接:[A framework and algorithms for circular drawings of graphs]()。<br />
Circular 布局将所有节点布局在一个圆环上,可以选择节点在圆环上的排列顺序。可以通过参数的配置扩展出环的分组布局、螺旋形布局等。原文链接:
<a href='https://www.sciencedirect.com/science/article/pii/S1570866705000031' target='_blank'>A framework and algorithms for circular drawings of graphs</a>
<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-3idTK1xa6wAAAAAAAAAAABkARQnAQ' width=270 />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*_nLORItzM5QAAAAAAAAAAABkARQnAQ' width=270 />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*6J6BRIjmXKAAAAAAAAAAAABkARQnAQ' width=270 />
@ -250,6 +290,10 @@ Circular 布局将所有节点布局在一个圆环上,可以选择节点在
**类型** Number<br />**默认值**1<br />**是否必须**false<br />**说明**:从第一个节点到最后节点之间相隔多少个 2*PI
#### workerEnabled
**类型**: Boolean<br />**默认值**: false<br />**是否必须**: false<br />**说明**: 是否启用 web-worker 以防布局计算时间过长阻塞页面交互
### 方法
与父类 Layout 的方法相同。使用该布局时不需要关心内部方法的调用,由 G6 控制。
@ -272,14 +316,15 @@ const graph = new G6.Graph({
ordering: 'degree', // 可选
angleRatio: 1 // 可选
}
);
});
```
## Radial
Radial 布局是将图布局成辐射状的布局方法。以一个 focusNode 为中心,其余节点按照与 focusNode 的度数关系排列在不同距离的环上。距离 focusNode 一度的节点布局在与其最近的第一个环上,距离 focusNode 二度的节点布局在第二个环上,以此类推。算法原文链接:[More Flexible Radial Layout](http://emis.ams.org/journals/JGAA/accepted/2011/BrandesPich2011.15.1.pdf)。
Radial 布局是将图布局成辐射状的布局方法。以一个 focusNode 为中心,其余节点按照与 focusNode 的度数关系排列在不同距离的环上。距离 focusNode 一度的节点布局在与其最近的第一个环上,距离 focusNode 二度的节点布局在第二个环上,以此类推。算法原文链接:
<a href='http://emis.ams.org/journals/JGAA/accepted/2011/BrandesPich2011.15.1.pdf' target='_blank'>More Flexible Radial Layout</a>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GAFjRJeAoAsAAAAAAAAAAABkARQnAQ' width=600 />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GAFjRJeAoAsAAAAAAAAAAABkARQnAQ' width=450 />
### 属性
@ -304,13 +349,32 @@ Radial 布局是将图布局成辐射状的布局方法。以一个 focusNode
#### preventOverlap
**类型**Boolean<br />**默认值**false<br />**是否必须**false<br />**说明**:是否防止重叠,必须配合下面属性 [`nodeSize`](#xWjHN) ,只有设置了与当前图节点大小相同的 `nodeSize` 值,才能够进行节点重叠的碰撞检测
**类型**Boolean<br />**默认值**false<br />**是否必须**false<br />**说明**:是否防止重叠,必须配合下面属性 `nodeSize`,只有设置了与当前图节点大小相同的 `nodeSize` 值,才能够进行节点重叠的碰撞检测
#### nodeSize
**类型** Number<br />**默认值**10<br />**是否必须**false<br />**说明**:节点大小(直径)。用于防止节点重叠时的碰撞检测
#### nodeSpacing
**类型**: Number / Function<br />**默认值**: 0<br />**是否必须**: false
<br />**示例**: Example 1: 10
<br />Example 2:  
```javascript
d => {
  // d is a node
  if (d.id === 'node1') {
    return 100;
  }
  return 10;
}
```
<br />**描述**:
`preventOverlap``true` 时生效, 防止重叠时节点边缘间距的最小值。可以是回调函数, 为不同节点设置不同的最小间距, 如示例 2 所示
#### maxPreventOverlapIteration
**类型** Number<br />**默认值**200<br />**是否必须**false<br />**说明**:防止重叠步骤的最大迭代次数
@ -328,6 +392,19 @@ Radial 布局是将图布局成辐射状的布局方法。以一个 focusNode
> preventOverlap = false。preventOverlap = falsestrictRadial = true。preventOverlap = falsestrictRadial = false。
#### sortBy
**类型**: String<br />**默认值**: undefined<br />**是否必须**: false<br />**说明**: 同层节点布局后相距远近的依据。默认 `undefined` ,表示根据数据的拓扑结构(节点间最短路径)排布,即关系越近/点对间最短路径越小的节点将会被尽可能排列在一起;`'data'` 表示按照节点在数据中的顺序排列,即在数据顺序上靠近的节点将会尽可能排列在一起;也可以指定为节点数据中的某个字段名,例如 `'cluster'`、`'name'` 等(必须在数据中存在)
#### sortStrength
**类型**: Number<br />**默认值**: 10<br />**是否必须**: false<br />**说明**: 同层节点根据 `sortBy` 排列的强度,数值越大,`sortBy` 指定的方式计算出距离越小的越靠近。`sortBy` 不为 `undefined` 时生效
#### workerEnabled
**类型**: Boolean<br />**默认值**: false<br />**是否必须**: false<br />**说明**: 是否启用 web-worker 以防布局计算时间过长阻塞页面交互
### 方法
与父类 Layout 的方法相同。使用该布局时不需要关心内部方法的调用,由 G6 控制。
@ -341,7 +418,7 @@ const graph = new G6.Graph({
width: 1000,
height: 600,
layout: {
type: 'circular',
type: 'radial',
center: [ 200, 200 ], // 可选,默认为图的中心
linkDistance: 50, // 可选,边长
maxIteration: 1000, // 可选
@ -350,8 +427,9 @@ const graph = new G6.Graph({
preventOverlap: true, // 可选,必须配合 nodeSize
nodeSize: 30, // 可选
strictRadial: false // 可选
workerEnabled: true // 可选,开启 web-worker
}
);
});
```
## Dagre
@ -370,8 +448,6 @@ Dagre 是一种层次布局。
- 'LR':从左至右布局;
- 'RL':从右至左布局。
<br />
#### align
**类型** String<br />**可选值**'UL' | 'UR' | 'DL' | 'DR'<br />**默认值**'UL'<br />**是否必须**false<br />**说明**节点对齐方式。UupperDdownLleftRright
@ -418,6 +494,10 @@ Dagre 是一种层次布局。
**类型** Boolean<br />**默认值**true<br />**是否必须**false<br />**说明**:是否保留布局连线的控制点
#### workerEnabled
**类型**: Boolean<br />**默认值**: false<br />**是否必须**: false<br />**说明**: 是否启用 web-worker 以防布局计算时间过长阻塞页面交互
### 方法
与父类 Layout 的方法相同。使用该布局时不需要关心内部方法的调用,由 G6 控制。
@ -437,7 +517,7 @@ const graph = new G6.Graph({
ranksep: 50, // 可选
controlPoints: true // 可选
}
);
});
```
## Concentric
@ -454,7 +534,7 @@ Concentric 布局为同心圆布局,用户可以指定节点某个属性为排
#### preventOverlap
**类型**Boolean<br />**默认值**false<br />**是否必须**false<br />**说明**:是否防止重叠,必须配合下面属性 [`nodeSize`](https://www.yuque.com/antv/g6/ngp0vg#xWjHN) ,只有设置了与当前图节点大小相同的 `nodeSize` 值,才能够进行节点重叠的碰撞检测
**类型**Boolean<br />**默认值**false<br />**是否必须**false<br />**说明**:是否防止重叠,必须配合下面属性 `nodeSize`,只有设置了与当前图节点大小相同的 `nodeSize` 值,才能够进行节点重叠的碰撞检测
#### nodeSize
@ -482,13 +562,17 @@ Concentric 布局为同心圆布局,用户可以指定节点某个属性为排
#### maxLevelDiff
**类型** Number<br />**默认值:**undefined<br />**是否必须**false<br />**说明**:每一层同心值的求和。若为 undefined则将会被设置为 maxValue / 4 ,其中 maxValue 为最大的排序依据的属性值。例如,若 sortBy='degree',则 maxValue 为所有节点中度数最大的节点的度数
**类型** Number<br />**默认值:**undefined<br />**是否必须**false<br />**说明**:每一层同心值的求和。若为 undefined则将会被设置为 maxValue / 4 ,其中 maxValue 为最大的排序依据的属性值。例如,若 `sortBy``'degree'`,则 maxValue 为所有节点中度数最大的节点的度数
#### sortBy
**类型** String<br />**默认值**undefined<br />**是否必须**false<br />**说明**:指定排序的依据(节点属性名),数值越高则该节点被放置得越中心。若为 undefined则会计算节点的度数度数越高节点将被放置得越中心
#### workerEnabled
**类型**: Boolean<br />**默认值**: false<br />**是否必须**: false<br />**说明**: 是否启用 web-worker 以防布局计算时间过长阻塞页面交互
### 方法
与父类 Layout 的方法相同。使用该布局时不需要关心内部方法的调用,由 G6 控制。
@ -512,15 +596,16 @@ const graph = new G6.Graph({
clockwise: false, // 可选
maxLevelDiff: 10, // 可选
sortBy: 'degree' // 可选
workerEnabled: true // 可选,开启 web-worker
}
);
});
```
## Grid
Grid 布局是将所有节点通过某种指定属性排序后,整齐地放置在网格上。
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Oh6mRLVEBBIAAAAAAAAAAABkARQnAQ' width=850 />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Oh6mRLVEBBIAAAAAAAAAAABkARQnAQ' width=650 />
### 属性
@ -529,7 +614,7 @@ Grid 布局是将所有节点通过某种指定属性排序后,整齐地放置
#### preventOverlap
**类型**Boolean<br />**默认值**false<br />**是否必须**false<br />**说明**:是否防止重叠,必须配合下面属性 [`nodeSize`](https://www.yuque.com/antv/g6/ngp0vg#xWjHN) ,只有设置了与当前图节点大小相同的 `nodeSize` 值,才能够进行节点重叠的碰撞检测
**类型**Boolean<br />**默认值**false<br />**是否必须**false<br />**说明**:是否防止重叠,必须配合下面属性 `nodeSize`,只有设置了与当前图节点大小相同的 `nodeSize` 值,才能够进行节点重叠的碰撞检测
#### nodeSize
@ -555,6 +640,9 @@ Grid 布局是将所有节点通过某种指定属性排序后,整齐地放置
#### sortBy
**类型** String<br />**默认值**undefined<br />**是否必须**false<br />**说明**:指定排序的依据(节点属性名),数值越高则该节点被放置得越中心。若为 undefined则会计算节点的度数度数越高节点将被放置得越中心
#### workerEnabled
**类型**: Boolean<br />**默认值**: false<br />**是否必须**: false<br />**说明**: 是否启用 web-worker 以防布局计算时间过长阻塞页面交互
### 方法
与父类 Layout 的方法相同。使用该布局时不需要关心内部方法的调用,由 G6 控制。
@ -568,7 +656,7 @@ const graph = new G6.Graph({
width: 1000,
height: 600,
layout: {
type: 'concentric',
type: 'grid',
begin: [ 0, 0 ], // 可选,
preventOverlap: true, // 可选,必须配合 nodeSize
preventOverlapPdding: 20, // 可选
@ -577,6 +665,7 @@ const graph = new G6.Graph({
rows: 5, // 可选
cols: 5, // 可选
sortBy: 'degree' // 可选
workerEnabled: true // 可选,开启 web-worker
}
);
});
```

View File

@ -16,7 +16,7 @@ const graph = new G6.Graph({
});
```
The configurations of each layout algorithms are different. Please refer to corresponding API of layout.
The configurations of each layout algorithms are different. Please refer to corresponding API of each layout in this directory.
<br />When `layout` is not assigned on graph:
- If there are `x` and `y` in node data, the graph will render with these information;
@ -35,7 +35,7 @@ Initialize the layout.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| data | Object | true | 布局中使用的数据 |
| data | Object | true | The data for the layout |

View File

@ -1,12 +1,12 @@
---
title: TreeGraph
title: TreeGraph Layout
order: 2
---
## CompactBox
CompactBox is the default layout for TreeGraph. It will consider the bounding box of each node when layout. It comes from classical [ReingoldTilford tidy layout algorithm](http://emr.cs.iit.edu/~reingold/tidier-drawings.pdf).
CompactBox is the default layout for TreeGraph. It will consider the bounding box of each node when layout. It comes from classical <a href='http://emr.cs.iit.edu/~reingold/tidier-drawings.pdf' target='_blank'>ReingoldTilford tidy layout algorithm</a>.
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*z-ESRoHTpvIAAAAAAAAAAABkARQnAQ' width=850 />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*z-ESRoHTpvIAAAAAAAAAAABkARQnAQ' width=650 />
### Configuration
@ -38,6 +38,16 @@ CompactBox is the default layout for TreeGraph. It will consider the bounding bo
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*ZFCiTLwCoAYAAAAAAAAAAABkARQnAQ' width=102/>
#### getId
**Type**: Function<br />**Example**:
```javascript
(d) => {
// d is a node
return d.id + '_node';
}
```
**Required**: false<br />**Description**: Sets the id for each node
#### getWidth
**Type**: Number | Function<br />**Example**:
```javascript
@ -93,7 +103,7 @@ CompactBox is the default layout for TreeGraph. It will consider the bounding bo
## Dendrogram
[Dendrogram](https://en.wikipedia.org/wiki/Dendrogram) arranges all the leaves on the same level. It is appropriate for hierarchical clustering.
<a href='https://en.wikipedia.org/wiki/Dendrogram' target='_blank'>Dendrogram</a> arranges all the leaves on the same level. It is appropriate for hierarchical clustering. It does not consider the node size, which will be regarded as 1px.
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*zX7tSLqBvwcAAAAAAAAAAABkARQnAQ' width=400 />
@ -147,7 +157,7 @@ Indented layout represents the hierarchy by indent between them. Each node will
### Configuration
#### direction
**Type**: String<br />**Options**: 'LR' | 'RL' | 'H'<br />**Default**: 'LR'<br />**Required**: false<br />**Description**: The direction of layout.
**Type**: String<br />**Options**: 'LR' | 'RL' | 'H'<br />**Default**: 'LR'<br />**Required**: false<br />**Description**: The direction of layout:
- LR —— Root is on the left, layout from the left to the right(left image below)<br />
- RL —— Root is on the right, layout from the right to the left(center image below)<br />
@ -156,6 +166,7 @@ Indented layout represents the hierarchy by indent between them. Each node will
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*mq6YSIKrAt0AAAAAAAAAAABkARQnAQ' width=110 />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*VGEnRbpvxlUAAAAAAAAAAABkARQnAQ' width=90 />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Vek6RqtUXNcAAAAAAAAAAABkARQnAQ' width=160 />
> (Left)LR. (Center)RL. (Right)H.
#### indent
@ -170,7 +181,7 @@ Indented layout represents the hierarchy by indent between them. Each node will
return 100;
}
```
**Required**: false<br />**Description**: The width of node
**Required**: false<br />**Description**: The width of each node
#### getHeight
**Type**: Number | Function<br />**Example**:
@ -181,7 +192,7 @@ Indented layout represents the hierarchy by indent between them. Each node will
return 100;
}
```
**Required**: false<br />**Description**: The height of node
**Required**: false<br />**Description**: The height of each node
#### getSide
**Type**: Function<br />**Example**:
@ -222,7 +233,7 @@ Mindmap arranged the nodes with same depth on the same level. Different from com
return 100;
}
```
**Required**: false<br />**Description**: The width of node
**Required**: false<br />**Description**: The width of each node
#### getHeight
**Type**: Number | Function<br />**Example**:
@ -233,7 +244,7 @@ Mindmap arranged the nodes with same depth on the same level. Different from com
return 100;
}
```
**Required**: false<br />**Description**: The height of node
**Required**: false<br />**Description**: The height of each node
#### getHGap
@ -269,4 +280,4 @@ Mindmap arranged the nodes with same depth on the same level. Different from com
return 'left';
}
```
**Default**: 'right'<br />**Required**: false<br />**Description**: The callback function of node position(left or right of root node). Only affects the nodes which are connected to the root node directly. And the descendant nodes will be placed according to it.
**Default**: 'right'<br />**Required**: false<br />**Description**: The callback function of node position(left or right of root node). Only affects the nodes which are connected to the root node directly. And the descendant nodes will be placed according to it

View File

@ -1,12 +1,12 @@
---
title: TreeGraph
title: TreeGraph Layout
order: 2
---
## CompactBox 紧凑树布局
紧凑盒树布局。这是树图的默认布局,其特点是布局时统合考虑每个树节点的包围盒,由经典的[ReingoldTilford tidy布局算法](http://emr.cs.iit.edu/~reingold/tidier-drawings.pdf)演进而来,适合于脑图等应用场景。
紧凑盒树布局。这是树图的默认布局,其特点是布局时统合考虑每个树节点的包围盒,由经典的 <a href='http://emr.cs.iit.edu/~reingold/tidier-drawings.pdf' target='_blank'>ReingoldTilford tidy 布局算法</a>演进而来,适合于脑图等应用场景。
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*z-ESRoHTpvIAAAAAAAAAAABkARQnAQ' width=850 />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*z-ESRoHTpvIAAAAAAAAAAABkARQnAQ' width=650 />
### 属性
@ -38,6 +38,17 @@ order: 2
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*E0c8TIYRPYoAAAAAAAAAAABkARQnAQ' width=100 />
#### getId
**类型**: Function<br />**示例**:
```javascript
(d) => {
// d is a node
return d.id + '_node';
}
```
**是否必须**: false<br />**说明**: 节点 id 的回调函数
#### getWidth
**类型**Number | Function<br />**示例**
```javascript
@ -93,14 +104,14 @@ order: 2
## Dendrogram 生态树布局
[生态树](https://en.wikipedia.org/wiki/Dendrogram)布局。特点是所有子节点布局在同一层级,适用于表示层次聚类。
<a href='https://en.wikipedia.org/wiki/Dendrogram' target='_blank'>生态树</a>布局的特点是所有子节点布局在同一层级,不考虑节点大小,每个节点被当成 1px 处理。适用于表示层次聚类。
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*zX7tSLqBvwcAAAAAAAAAAABkARQnAQ' width=400 />
### 属性
#### direction
**类型**String<br />**可选值**'LR' | 'RL' | 'TB' | 'BT' | 'H' | 'V'<br />**默认值**'LR'<br />**是否必须**false<br />**说明**:树布局的方向,默认为,其他选项说明
**类型**String<br />**可选值**'LR' | 'RL' | 'TB' | 'BT' | 'H' | 'V'<br />**默认值**'LR'<br />**是否必须**false<br />**说明**:树布局的方向,默认为 `'LR'`,其他选项说明
- TB —— 根节点在上,往下布局
@ -150,7 +161,7 @@ order: 2
### 属性
#### direction
**类型**String<br />**可选值**'LR' | 'RL' | 'H'<br />**默认值**'LR'<br />**是否必须**false<br />**说明**:树布局的方向,默认为,其他选项说明
**类型**String<br />**可选值**'LR' | 'RL' | 'H'<br />**默认值**'LR'<br />**是否必须**false<br />**说明**:树布局的方向,默认为 `'LR'`,其他选项说明
- LR —— 根节点在左,往右布局(下图左)<br />
- RL —— 根节点在右,往左布局(下图中)<br />
@ -207,7 +218,7 @@ order: 2
### 属性
#### direction
**类型**String<br />**可选值**'H' | 'V'<br />**默认值**'H'<br />**是否必须**false<br />**说明**:树布局的方向,默认为,其他选项说明
**类型**String<br />**可选值**'H' | 'V'<br />**默认值**'H'<br />**是否必须**false<br />**说明**:树布局的方向,默认为 `'H'`,其他选项说明
- Hhorizontal水平—— 根节点的子节点分成两部分横向放置在根节点左右两侧

View File

@ -69,11 +69,7 @@ Get the current source item (node) of the edge.
**Return**
- The type of return value: Node;
<<<<<<< HEAD
- Returns the item of source node.
=======
- Return the item of source node.
>>>>>>> feat: english version of API
**Usage**
@ -96,11 +92,7 @@ Get the current target item (node) of the edge.
**Return**
- The type of return value: Node;
<<<<<<< HEAD
- Returns the item of target node.
=======
- Return the item of target node.
>>>>>>> feat: english version of API
**Usage**

View File

@ -3,7 +3,7 @@ title: Edge
order: 1
---
Edge 继承自 Item,所以,Item 的方法在 Edge 实例中都可以使用。
Edge 继承自 Item。所以 Item 的方法在 Edge 实例中都可以使用。
## setSource(source)

View File

@ -3,7 +3,7 @@ title: Item
order: 0
---
Item is the object of node / edge G6.
Item is the object of node / edge in G6.
## Update
@ -67,7 +67,7 @@ Update the position of the item. We recommend to call this function for single i
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| cfg | Object | true | The configurations of the item, including x and y. The x and y value in source data model will take effect if there are no x and y in `cfg`. |
| cfg | Object | true | The configurations of the item, including `x` and `y`. The x and y value in source data model will take effect if there are no `x` and `y` in `cfg`. |
@ -210,7 +210,7 @@ const type = item.get('type')
### enableCapture(enable)
Whether enable the item to be picked and enable its interaction events.
Whether to enable the item to be picked and enable its interaction events.
**Parameters**

View File

@ -23,10 +23,10 @@ Item 是 G6 中绘图元素实例,目前包含节点和边的实例。对于
| 名称 | 类型 | 是否必选 | 描述 |
| --- | --- | --- | --- |
| id | String | true | 元素ID必须唯一 |
| id | String | true | 元素 ID必须唯一 |
| style | Object | false | 元素样式 |
| shape | String | false | 元素的形状,不传则使用默认值 |
| label | String | false | 元素label有该字段时默认会渲染 label |
| label | String | false | 元素 label有该字段时默认会渲染 label |
**用法**
@ -67,7 +67,7 @@ item.refresh()
| 名称 | 类型 | 是否必选 | 描述 |
| --- | --- | --- | --- |
| cfg | Object | true | 元素配置项,包括 x、y 属性,如果参数中无 x、y 属性,则更新时使用数据项中的值。 |
| cfg | Object | true | 元素配置项,包括 `x``y` 属性,如果参数中无 `x``y` 属性,则更新时使用数据项中的值。 |
@ -92,7 +92,7 @@ item.updatePosition(cfg1)
## 销毁
### destroy()
销毁元素,主要包括停止动画、删除 group 中的所有元素、清空配置项、设置 destroyed 为 true 等操作。
销毁元素,主要包括停止动画、删除 group 中的所有元素、清空配置项、设置 `destroyed``true` 等操作。
**用法**
@ -115,8 +115,8 @@ item.destroy()
| 名称 | 类型 | 描述 |
| --- | --- | --- |
| x | number | 视口x坐标 |
| y | number | 视口y坐标 |
| x | number | 视口 x 坐标 |
| y | number | 视口 y 坐标 |
| width | number | bbox 宽度 |
| height | number | bbox 高度 |
| centerX | number | 中心点 x 坐标 |
@ -439,7 +439,7 @@ const style = item.getStateStyle('selected')
**返回值**
- 返回值类型:object | undefined
- 返回值类型:Object | undefined
- 如果存在 keyShape ,则返回 `keyShape` 的样式,否则返回 `undefined`

View File

@ -7,23 +7,21 @@ Node inherits from item. The functions of Item are also available for Node.
## lock()
> New feature of v3.1.4.
Lock the current node. The locked node will not response the drag event any more.
Tips: the locked node still can be moved while dragging and zooming the canvas. If you want to fix the node in these two situations, please refer to (Fix the node while dragging the canvas)[/zh/docs/manual/advanced/lock-node#拖动画布时候不处理锁定的节点] and (Fix the node while zooming the canvas)[/zh/docs/manual/advanced/lock-node#拖动画布时候不处理锁定的节点] .
Tips: the locked node still can be moved while dragging and zooming the canvas. If you want to fix the node in these two situations, please refer to [Fix the Locked Node While Dragging](/en/docs/manual/advanced/lock-node#fix-the-locked-node-while-dragging) and [Fix the Locked Node while Zooming](/en/docs/manual/advanced/lock-node#fix-the-locked-node-while-zooming) to register a custom Behavior.
**Usage**
```javascript
const node = graph.findById('node')
node.lock()
const node = graph.findById('node');
node.lock();
```
## unlock()
> New feature of V3.1.4.
Unlock the locked node.
@ -31,13 +29,12 @@ Unlock the locked node.
**Usage**
```javascript
const node = graph.findById('node')
node.unlock()
const node = graph.findById('node');
node.unlock();
```
## hasLocked()
> New feature of V3.1.4.
Query the lock state of the node.
@ -51,8 +48,8 @@ Query the lock state of the node.
**Usage**
```javascript
const node = graph.findById('node')
const hasLocked = node.hasLocked()
const node = graph.findById('node');
const hasLocked = node.hasLocked();
```
@ -69,7 +66,7 @@ Get the related edges (the node is the source or the target of the edge) of the
**Usage**
```javascript
// Get the related edges
const edges = node.getEdges()
const edges = node.getEdges();
```
@ -86,7 +83,7 @@ Get the related in-edges, whose target is the node.
**Usage**
```javascript
// Get the related in-edges
const edges = node.getInEdges()
const edges = node.getInEdges();
```
@ -103,7 +100,7 @@ Get the related out-edges, whose source is the node.
**Usage**
```javascript
// Get the related out-edges
const edges = node.getOutEdges()
const edges = node.getOutEdges();
```
@ -134,7 +131,7 @@ Get all the anchor points of the node.
**Usage**
```javascript
// Get the anchor points of the node
const anchor = node.getAnchorPoints()
const anchor = node.getAnchorPoints();
```
@ -152,7 +149,7 @@ Get the nearest anchor point of the node to `point`.
**Return**
- The type of return value: object
- The type of return value: Object
- Returns (x, y) of the found anchor point. If there is no anchor point found, returns the center of the node.
@ -161,9 +158,9 @@ Get the nearest anchor point of the node to `point`.
const point = {
x: 100,
y: 105
}
};
// Get the anchor point which is nearest to the point
const linkPoint = node.getLinkPoint(point)
const linkPoint = node.getLinkPoint(point);
```
@ -189,7 +186,7 @@ Get the (x, y) of the anchor point with the `index`.
**Usage**
```javascript
// Get the first anchor point of the node
const anchor = node.getLinkPointByAnchor(0)
const anchor = node.getLinkPointByAnchor(0);
```
## addEdge(edge)
@ -208,8 +205,8 @@ Add the `edge` to the node.
```javascript
const edge = new Edge({
// TODO
})
node.addEdge(edge)
});
node.addEdge(edge);
```
@ -227,6 +224,6 @@ Remove the `edge` from the node.
**Usage**
```javascript
const edge = // TODO
node.removeEdge(edge)
const edge = graph.findById('edge1');
node.removeEdge(edge);
```

View File

@ -3,7 +3,7 @@ title: Node
order: 1
---
Node继承自Item所以Item上面的方法在Node实例中都可以调用。
Node 继承自 Item。所以 Item 上面的方法在 Node 实例中都可以调用。
## lock()
@ -11,14 +11,14 @@ Node继承自Item所以Item上面的方法在Node实例中都可以调用
锁定当前节点,锁定节点后,该节点不再响应拖动节点的事件。
提示:锁定节点后,拖动画布和缩放画布的操作依然对该节点有效。如果想在锁定节点后,不响应拖动画布和缩放的事件,需要自定义拖动画布和缩放的 Behavior具体可参考 (锁定节点不响应拖动画布的事件)[/zh/docs/manual/advanced/lock-node#拖动画布时候不处理锁定的节点] 和 (锁定节点不响应缩放事件)[/zh/docs/manual/advanced/lock-node#拖动画布时候不处理锁定的节点]
提示:锁定节点后,拖动画布和缩放画布的操作依然对该节点有效。如果想在锁定节点后,不响应拖动画布和缩放的事件,需要自定义拖动画布和缩放的 Behavior具体可参考 [锁定节点不响应拖动画布的事件](/zh/docs/manual/advanced/lock-node#拖动画布时候不处理锁定的节点) 和 [锁定节点不响应缩放事件](/zh/docs/manual/advanced/lock-node#拖动画布时候不处理锁定的节点)
**用法**
```javascript
const node = graph.findById('node')
node.lock()
const node = graph.findById('node');
node.lock();
```
@ -31,8 +31,8 @@ node.lock()
**用法**
```javascript
const node = graph.findById('node')
node.unlock()
const node = graph.findById('node');
node.unlock();
```
@ -44,15 +44,15 @@ node.unlock()
**返回值**
- 返回值类型:boolean
- 返回值类型:Boolean
- 返回 true 表示当前解锁处于锁定状态,否则表示未锁定。
**用法**
```javascript
const node = graph.findById('node')
const hasLocked = node.hasLocked()
const node = graph.findById('node');
const hasLocked = node.hasLocked();
```
@ -69,7 +69,7 @@ const hasLocked = node.hasLocked()
**用法**
```javascript
// 获取与 node 关联的所有边
const edges = node.getEdges()
const edges = node.getEdges();
```
@ -86,7 +86,7 @@ const edges = node.getEdges()
**用法**
```javascript
// 获取与 node 关联的所有入边
const edges = node.getInEdges()
const edges = node.getInEdges();
```
@ -103,7 +103,7 @@ const edges = node.getInEdges()
**用法**
```javascript
// 获取与 node 关联的所有出边
const edges = node.getOutEdges()
const edges = node.getOutEdges();
```
@ -134,7 +134,7 @@ const edges = node.getOutEdges()
**用法**
```javascript
// 获取定义在节点上的锚点数据
const anchor = node.getAnchorPoints()
const anchor = node.getAnchorPoints();
```
@ -161,15 +161,15 @@ const anchor = node.getAnchorPoints()
const point = {
x: 100,
y: 105
}
};
// 获取连接点
const linkPoint = node.getLinkPoint(point)
const linkPoint = node.getLinkPoint(point);
```
## getLinkPointByAnchor(index)
根据锚点索引获取连接点的x、y坐标。
根据锚点索引获取连接点的 x、y 坐标。
**参数**
@ -189,7 +189,7 @@ const linkPoint = node.getLinkPoint(point)
**用法**
```javascript
// 获取定义在节点上的第一个锚点
const anchor = node.getLinkPointByAnchor(0)
const anchor = node.getLinkPointByAnchor(0);
```
## addEdge(edge)
@ -208,8 +208,8 @@ const anchor = node.getLinkPointByAnchor(0)
```javascript
const edge = new Edge({
// TODO
})
node.addEdge(edge)
});
node.addEdge(edge);
```
@ -227,6 +227,6 @@ node.addEdge(edge)
**用法**
```javascript
const edge = // TODO
node.removeEdge(edge)
const edge = graph.findById('edge1');
node.removeEdge(edge);
```

View File

@ -1,61 +0,0 @@
---
title: Properties of Edge
order: 1
---
## Common Property
| Name | Description | Remark |
| --- | --- | --- |
| fill | The color or gradient color for filling. | The corresponding property in canvas is `fillStyle`. |
| stroke | The color, gradient color, or pattern for stroke. | The corresponding property in canvas is `strokeStyle`. |
| shadowColor | The color for shadow. | |
| shadowBlur | The blur level for shadow. | Larger the value, more blur. |
| shadowOffsetX | The horizontal offset of the shadow. | |
| shadowOffsetY | The vertical offset of the shadow. | |
| opacity | The opacity (alpha value) of the shape. | The corresponding property in canvas is `globalAlpha`. |
## Path
⚠️**Attention:** when the edge is too thin to be hitted by mouse, set **lineAppendWidth** to enlarge the hitting area.
**Property**
| Name | Description | Remark |
| --- | --- | --- |
| path | The path. | It can be a String, or an Array of path. |
| startArrow | The arrow on the start of the path. | When `startArrow` is `true`, show a default arrow on the start of the path. User can custom an arrow by path. |
| endArrow | The arrow on the end of the path. | When `startArrow` is `true`, show a default arrow on the end of the path. User can custom an arrow by path. |
| lineAppendWidth | The hitting area of the path. | Enlarge the hitting area by enlarging its value. |
| lineCap | The style of two ends of the path. | |
| lineJoin | The style of the intersection of two path. | |
| lineWidth | The line width of the current path. | |
| miterLimit | The maximum miter length. | |
| lineDash | The style of the dash line. | It is an array that describes the length of gaps and line segments. If the number of the elements in the array is odd, the elements will be dulplicated. Such as [5, 15, 25] will be regarded as [5, 15, 25, 5, 15, 25]. |
**Usage**
```javascript
group.addShape('path', {
attrs: {
startArrow: {
// The custom arrow is a path centered at (0, 0), and points to the positive direction of x-axis
path: 'M 10,0 L -10,-10 L -10,10 Z',
d: 10
},
endArrow: {
// The custom arrow is a path centered at (0, 0), and points to the positive direction of x-axis
path: 'M 10,0 L -10,-10 L -10,10 Z',
d: 10
},
path: [
[ 'M', 100, 100 ],
[ 'L', 200, 200 ]
],
stroke: '#000',
lineWidth: 8,
lineAppendWidth: 5
}
});
```

View File

@ -1,59 +0,0 @@
---
title: 边属性
order: 1
---
## 通用属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| fill | 设置用于填充绘画的颜色、渐变或模式 | 对应 canvas 属性 `fillStyle` |
| stroke | 设置用于笔触的颜色、渐变或模式 | 对应 canvas 属性 `strokeStyle` |
| shadowColor | 设置用于阴影的颜色 | |
| shadowBlur | 设置用于阴影的模糊级别 | 数值越大,越模糊 |
| shadowOffsetX | 设置阴影距形状的水平距离 | |
| shadowOffsetY | 设置阴影距形状的垂直距离 | |
| opacity | 设置绘图的当前 alpha 或透明值 | 对应 canvas 属性 `globalAlpha` |
## 线条 Path
特别注意:当边太细时候点击不中时,请设置 **lineAppendWidth** 属性值。
**属性**
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| path | 线条路径 | 可以是 String 形式,也可以是线段的数组。 |
| startArrow | 起始端的箭头 | 为 `true` 时为默认的箭头效果,也可以是一个自定义箭头 |
| endArrow | 末尾端的箭头 | 为 `true` 时为默认的箭头效果,也可以是一个自定义箭头 |
| lineAppendWidth | 边的击中范围 | 提升边的击中范围,扩展响应范围,数值越大,响应范围越广 |
| lineCap | 设置线条的结束端点样式 | |
| lineJoin | 设置两条线相交时,所创建的拐角形状 | |
| lineWidth | 设置当前的线条宽度 | |
| miterLimit | 设置最大斜接长度 | |
| lineDash | 设置线的虚线样式,可以指定一个数组 | 一组描述交替绘制线段和间距(坐标空间单位)长度的数字。 如果数组元素的数量是奇数, 数组的元素会被复制并重复。例如, [5, 15, 25] 会变成 [5, 15, 25, 5, 15, 25]。 |
**用法**
```javascript
group.addShape('path', {
attrs: {
startArrow: {
path: 'M 10,0 L -10,-10 L -10,10 Z', // 自定义箭头为中心点在(0, 0),指向 x 轴正方向的 path
d: 10
},
endArrow: {
path: 'M 10,0 L -10,-10 L -10,10 Z', // 自定义箭头为中心点在(0, 0),指向 x 轴正方向的 path
d: 10
},
path: [
[ 'M', 100, 100 ],
[ 'L', 200, 200 ]
],
stroke: '#000',
lineWidth: 8,
lineAppendWidth: 5
}
});
```

View File

@ -1,223 +0,0 @@
---
title: Properties of Node
order: 0
---
### Common Property
**Property**
| Name | Description | Remark |
| --- | --- | --- |
| fill | The color or gradient color for filling. | The corresponding property in canvas is `fillStyle`. |
| stroke | The color, gradient color, or pattern for stroke. | The corresponding property in canvas is `strokeStyle`. |
| shadowColor | The color for shadow. | |
| shadowBlur | The blur level for shadow. | Larger the value, more blur. |
| shadowOffsetX | The horizontal offset of the shadow. | |
| shadowOffsetY | The vertical offset of the shadow. | |
| opacity | The opacity (alpha value) of the shape. | The corresponding property in canvas is `globalAlpha`. |
**Usage**
```javascript
group.addShape('rect', {
attrs: {
fill: 'red',
shadowOffsetX: 10,
shadowOffsetY: 10,
shadowColor: 'blue',
shadowBlur: 10,
opacity: 0.8
}
})
```
### Circle
**Property**
| Name | Description | Remark |
| --- | --- | --- |
| x | The x of the center of the circle. | |
| y | The y of the center of the circle. | |
| r | The radius of the circle. | |
**Usage**
```javascript
group.addShape('circle', {
attrs: {
x: 100,
y: 100,
r: 50,
fill: 'blue'
}
})
```
### Ellipse
**Property**
| Name | Description | Remark |
| --- | --- | --- |
| x | The x of the center of the ellipse. | |
| y | The y of the center of the ellipse. | |
| rx | The horizontal raidus of the ellipse. | |
| ry | The vertical raidus of the ellipse. | |
**Usage**
```javascript
group.addShape('ellipse', {
attrs: {
x: 100,
y: 100,
rx: 50,
ry: 50,
fill: 'blue'
}
})
```
### Fan
**Property**
| Name | Description | Remark |
| --- | --- | --- |
| x | The x of the center of the fan. | |
| y | The y of the center of the fan. | |
| rs | The horizontal raidus of the fan. | |
| re | The vertical raidus of the fan. | |
| startAngle | The start angle. | Radian system represented by Math.PI. |
| endAngle | The end angle. | |
| clockwise | It will be rendered clockwisely if it is `true`, counterclockwisely if it is `false`. | |
**Usage**
```javascript
group.addShape('fan', {
attrs: {
x: 50,
y: 50,
re: 40,
rs: 30,
startAngle: 1/2 * Math.PI,
endAngle: Math.PI,
clockwise: false,
fill: '#b7eb8f'
}
})
```
### Image
**Property**
| Name | Description | Remark |
| --- | --- | --- |
| x | The x of the left top of the image. | |
| y | The y of the left top of the image. | |
| width | The width of the image. | |
| height | The height of the image. | |
| img | The source of the image. | G6 supports multiple image formats: <br />- url<br />- ImageData<br />- Image<br />- canvas<br /> |
**Usage**
```javascript
group.addShape('image', {
attrs: {
x: 0,
y: 0,
img:'https://g.alicdn.com/cm-design/arms-trace/1.0.155/styles/armsTrace/images/TAIR.png'
}
})
```
### Marker
**Property**
| Name | Description | Remark |
| --- | --- | --- |
| x | The x of the center of the marker. | |
| y | The y of the center of the marker. | |
| r | The radius of the marker. | |
| symbol | The shape name. | There are several built-in shapes: `circle`, `square`, `diamond`, `triangle`, `triangle-down`. And user could custom a shape as marker. |
**Usage**
```javascript
group.addShape('marker', {
attrs: {
x: 10,
y: 10,
r: 10,
symbol: function(x, y, r) {
return [
[ 'M', x, y ],
[ 'L', x + r, y + r ],
[ 'L'x + r * 2, y ],
[ 'Z' ]
]
}
}
});
```
### Polygon
**Property**
| Name | Description | Remark |
| --- | --- | --- |
| points | The coordinates of the points on the polygon. | It is an array. |
**Usage**
```javascript
group.addShape('polygon', {
attrs: {
points:[[ 30, 30 ], [ 40, 20 ], [ 30, 50 ], [ 60, 100 ]],
fill: 'red'
}
});
```
### Rect
**Property**
| Name | Description | Remark |
| --- | --- | --- |
| x | The x of left top of the rect. | |
| y | The y of left top of the rect. | |
| width | The width of the rect. | |
| height | The height of the rect. | |
| radius | The border radius. | It can be an integer or an array, representing the border radii of lefttop, righttop, rightbottom, leftbotton respectively. <br />- `radius = 1` or `radius = [ 1 ]` is equal to `radius = [ 1, 1, 1, 1 ]`<br />- `radius = [ 1, 2 ]` is equal to `radius = [ 1, 2, 1, 2 ]`<br />- `radius: [ 1, 2, 3 ]` is equal to `radius: [ 1, 2, 3, 2 ]`<br /> |
**Usage**
```javascript
group.addShape('rect', {
attrs: {
x: 150,
y: 150,
width: 150,
height: 150,
stroke: 'black',
radius: [2, 4]
}
});
```

View File

@ -1,223 +0,0 @@
---
title: 节点属性
order: 0
---
### 通用属性
**属性**
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| fill | 设置用于填充绘画的颜色、渐变或模式 | 对应 canvas 属性`fillStyle` |
| stroke | 设置用于笔触的颜色、渐变或模式 | 对应 canvas 属性`strokeStyle` |
| shadowColor | 设置用于阴影的颜色 | |
| shadowBlur | 设置用于阴影的模糊级别 | 数值越大,越模糊 |
| shadowOffsetX | 设置阴影距形状的水平距离 | |
| shadowOffsetY | 设置阴影距形状的垂直距离 | |
| opacity | 设置绘图的当前 alpha 或透明值 | 对应canvas属性`globalAlpha` |
**用法**
```javascript
group.addShape('rect', {
attrs: {
fill: 'red',
shadowOffsetX: 10,
shadowOffsetY: 10,
shadowColor: 'blue',
shadowBlur: 10,
opacity: 0.8
}
})
```
### 圆图形 Circle
**属性**
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| x | 圆心的 x 坐标 | |
| y | 圆心的 y 坐标 | |
| r | 圆的半径 | |
**用法**
```javascript
group.addShape('circle', {
attrs: {
x: 100,
y: 100,
r: 50,
fill: 'blue'
}
})
```
### 椭圆图形 Ellipse
**属性**
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| x | 圆心的 x 坐标 | |
| y | 圆心的 y 坐标 | |
| rx | 水平半径 | |
| ry | 垂直半径 | |
**用法**
```javascript
group.addShape('ellipse', {
attrs: {
x: 100,
y: 100,
rx: 50,
ry: 50,
fill: 'blue'
}
})
```
### 扇形图形 Fan
**属性**
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| x | 扇形圆心的 x 坐标 | |
| y | 扇形圆心的 y 坐标 | |
| rs | 水平半径 | |
| re | 垂直半径 | |
| startAngle | 起点弧度 | 弧度制,即使用 Math.PI 表示 |
| endAngle | 终点弧度 | |
| clockwise | 为 `true` 时顺时针渲染,为 `false` 时逆时针渲染 | |
**用法**
```javascript
group.addShape('fan', {
attrs: {
x: 50,
y: 50,
re: 40,
rs: 30,
startAngle: 1/2 * Math.PI,
endAngle: Math.PI,
clockwise: false,
fill: '#b7eb8f'
}
})
```
### 图片图形 Image
**属性**
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| x | 图片左上角的 x 坐标 | |
| y | 图片左上角的 y 坐标 | |
| width | 图片宽度 | |
| height | 图片高度 | |
| img | 图片源 | G6 支持多种格式的图片:<br />- url<br />- ImageData<br />- Image<br />- canvas<br /> |
**用法**
```javascript
group.addShape('image', {
attrs: {
x: 0,
y: 0,
img:'https://g.alicdn.com/cm-design/arms-trace/1.0.155/styles/armsTrace/images/TAIR.png'
}
})
```
### 标记图形 Marker
**属性**
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| x | 中心的 x 坐标 | |
| y | 中心的 y 坐标 | |
| r | 形状半径 | |
| symbol | 指定形状 | 内置了一些常用形状,如圆形 `circle`,矩形 `square`,菱形 `diamond`,三角形 `triangle`,倒三角形 `triangle-down`,也可以是自定义的 path 路径。 |
**用法**
```javascript
group.addShape('marker', {
attrs: {
x: 10,
y: 10,
r: 10,
symbol: function(x, y, r) {
return [
[ 'M', x, y ],
[ 'L', x + r, y + r ],
[ 'L'x + r * 2, y ],
[ 'Z' ]
]
}
}
});
```
### 多边形图形 Polygon
**属性**
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| points | 多边形的所有端点坐标 | 数组形式 |
**用法**
```javascript
group.addShape('polygon', {
attrs: {
points:[[ 30, 30 ], [ 40, 20 ], [ 30, 50 ], [ 60, 100 ]],
fill: 'red'
}
});
```
### 矩形图形 Rect
**属性**
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| x | 矩形左上角的 x 坐标 | |
| y | 矩形左上角的 y 坐标 | |
| width | 矩形的宽度 | |
| height | 矩形的高度 | |
| radius | 定义圆角 | 支持整数或数组形式,分别对应左上、右上、右下、左下角的半径:<br />- radius 缩写为 1 或 [ 1 ] 相当于 [ 1, 1, 1, 1 ]<br />- radius 缩写为 [ 1, 2 ] 相当于 [ 1, 2, 1, 2 ]<br />- radius 缩写为 [ 1, 2, 3 ] 相当于 [ 1, 2, 3, 2 ]<br /> |
**用法**
```javascript
group.addShape('rect', {
attrs: {
x: 150,
y: 150,
width: 150,
height: 150,
stroke: 'black',
radius: [2, 4]
}
});
```

View File

@ -1,70 +0,0 @@
---
title: Properties of Text
order: 2
---
### Properties
| Name | Description | Remark |
| --- | --- | --- |
| fill | The color or gradient color for filling. | The corresponding property in canvas is `fillStyle`. |
| stroke | The color, gradient color, or pattern for stroke. | The corresponding property in canvas is `strokeStyle`. |
| shadowColor | The color for shadow. | |
| shadowBlur | The blur level for shadow. | Larger the value, more blur. |
| shadowOffsetX | The horizontal offset of the shadow. | |
| shadowOffsetY | The vertical offset of the shadow. | |
| opacity | The opacity (alpha value) of the shape. | The corresponding property in canvas is `globalAlpha`. |
| font | The font of the text. | |
| textAlign | The align way of the text. | Options: `'center'` / `'end'` / `'left'` / `'right'` / `'start'`. `'start'` by default. |
| textBaseline | The base line of the text. | Options: <br />`'top'` / `'middle'` / `'bottom'` / `'alphabetic'` / `'hanging'`. `'bottom'` by default. |
| fontStyle | The font style of the text. | The corresponding property in css is `font-style` |
| fontVariant | The font variant of the text. | The corresponding property in css is `font-variant` |
| fontWeight | The font weight of the text. | The corresponding property in css is `font-weight` |
| fontSize | The font size of the text. | The corresponding property in css is `font-size` |
| fontFamily | The font family of the text. | The corresponding property in css is `font-family` |
| autoRotate | Wheter rotate the text according to the edge automatically if it is a label of an edge. | |
### Case
```javascript
const data = {
nodes: [
{
id: 'node1',
x: 100,
y: 100,
shape: 'rect',
label: 'rect'
}
]
}
const graph = new G6.Graph({
container: 'mountNode',
width: 500,
height: 500
});
graph.data(data);
graph.render();
const node = graph.findById('node1')
graph.update(node, {
style: {
stroke: 'blue'
},
labelCfg: {
style: {
fill: 'red',
shadowOffsetX: 10,
shadowOffsetY: 10,
shadowColor: 'blue',
shadowBlur: 10
}
}
})
```
Modify the style of text of node as the code above, and we get the result:
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*euH9SLcS2IoAAAAAAAAAAABkARQnAQ' width=350>

View File

@ -1,94 +0,0 @@
---
title: Attributes of Text
order: 2
---
### Attributes
文本有以下可用的属性。
| Name | Description | Remark |
| --- | --- | --- |
<<<<<<< HEAD
| fill | 设置用于填充绘画的颜色、渐变或模式 | 对应 canvas 属性 `fillStyle` |
| stroke | 设置用于笔触的颜色、渐变或模式 | 对应 canvas 属性 `strokeStyle` |
| shadowColor | 设置用于阴影的颜色 | |
| shadowBlur | 设置用于阴影的模糊级别 | 数值越大,越模糊 |
| shadowOffsetX | 设置阴影距形状的水平距离 | |
| shadowOffsetY | 设置阴影距形状的垂直距离 | |
| opacity | 设置绘图的当前 alpha 或透明值 | 对应 canvas 属性 `globalAlpha` |
| font | 设置文本内容的当前字体属性 | |
| textAlign | 设置文本内容的当前对齐方式 | 支持的属性:`'center'` / `'end'` / `'left'` / `'right'` / `'start'`,默认值为 `'start'` |
| textBaseline | 设置在绘制文本时使用的当前文本基线 | 支持的属性: <br />`'top'` / `'middle'` / `'bottom'` / `'alphabetic'` / `'hanging'`。默认值为`'bottom'` |
| fontStyle | 字体样式 | 对应 `font-style` |
| fontVariant | 设置为小型大写字母字体 | 对应 `font-variant` |
| fontWeight | 字体粗细 | 对应 `font-weight` |
| fontSize | 字体大小 | 对应 `font-size` |
| fontFamily | 字体系列 | 对应 `font-family` |
| autoRotate | 是否自动旋转 | |
=======
| fill | The color or gradient color for filling. | The corresponding attribute in canvas is `fillStyle`. |
| stroke | The color, gradient color, or pattern for stroke. | The corresponding attribute in canvas is `strokeStyle`. |
| shadowColor | The color for shadow. | |
| shadowBlur | The blur level for shadow. | Larger the value, more blur. |
| shadowOffsetX | The horizontal offset of the shadow. | |
| shadowOffsetY | The vertical offset of the shadow. | |
| opacity | The opacity (alpha value) of the shape. | The corresponding attribute in canvas is `globalAlpha`. |
| font | The font of the text. | |
| textAlign | The align way of the text. | Options: `'center'` / `'end'` / `'left'` / `'right'` / `'start'`. `'start'` by default. |
| textBaseline | The base line of the text. | Options: <br />`'top'` / `'middle'` / `'bottom'` / `'alphabetic'` / `'hanging'`. `'bottom'` by default. |
| fontStyle | The font style of the text. | The corresponding attribute in css is `font-style` |
| fontVariant | The font variant of the text. | The corresponding attribute in css is `font-variant` |
| fontWeight | The font weight of the text. | The corresponding attribute in css is `font-weight` |
| fontSize | The font size of the text. | The corresponding attribute in css is `font-size` |
| fontFamily | The font family of the text. | The corresponding attribute in css is `font-family` |
| autoRotate | Wheter rotate according to the edge automatically. | |
>>>>>>> feat: english version of API
### Case
```javascript
const data = {
nodes: [
{
id: 'node1',
x: 100,
y: 100,
shape: 'rect',
label: 'rect'
}
]
}
const graph = new G6.Graph({
container: 'mountNode',
width: 500,
height: 500
});
graph.data(data);
graph.render();
const node = graph.findById('node1')
graph.update(node, {
style: {
stroke: 'blue'
},
labelCfg: {
style: {
fill: 'red',
shadowOffsetX: 10,
shadowOffsetY: 10,
shadowColor: 'blue',
shadowBlur: 10
}
}
})
```
<<<<<<< HEAD
通过以上代码修改 node 中文本的样式,效果如下图:
=======
Modify the style of text of node as the code above, and we get the result:
>>>>>>> feat: english version of API
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*euH9SLcS2IoAAAAAAAAAAABkARQnAQ' width=350>

View File

@ -0,0 +1,317 @@
---
title: Shape Properties
order: 4
---
Shape is the basic element on an item (node/edge). The `style` of a node or an edge corresponds to the shape properties of its keyShap (key shape). The `style` in `labelCfg` of a label on a node or an edge corresponds to the properties of text shape.
G6 has these shapes:
- [circle](#circle);
- [rect](#rect);
- [ellipse](#ellipse);
- [polygon](#polygon);
- [fan](#fan);
- [image](#image);
- [marker](#marker);
- [path](#path);
- [text](#text).
### Common Property
| Name | Description | Remark |
| --- | --- | --- |
| fill | The color or gradient color for filling. | The corresponding property in canvas is `fillStyle`. |
| stroke | The color, gradient color, or pattern for stroke. | The corresponding property in canvas is `strokeStyle`. |
| shadowColor | The color for shadow. | |
| shadowBlur | The blur level for shadow. | Larger the value, more blur. |
| shadowOffsetX | The horizontal offset of the shadow. | |
| shadowOffsetY | The vertical offset of the shadow. | |
| opacity | The opacity (alpha value) of the shape. | The corresponding property in canvas is `globalAlpha`. |
## Usage
```javascript
group.addShape('rect', {
attrs: {
fill: 'red',
shadowOffsetX: 10,
shadowOffsetY: 10,
shadowColor: 'blue',
shadowBlur: 10,
opacity: 0.8
}
})
```
### Circle
### Special Property
| Name | Description |
| --- | --- |
| x | The x of the center of the circle. |
| y | The y of the center of the circle. |
| r | The radius of the circle. |
### Usage
```javascript
group.addShape('circle', {
attrs: {
x: 100,
y: 100,
r: 50,
fill: 'blue'
}
})
```
### Ellipse
### Special Property
| Name | Description |
| --- | --- |
| x | The x of the center of the ellipse. |
| y | The y of the center of the ellipse. |
| rx | The horizontal raidus of the ellipse. |
| ry | The vertical raidus of the ellipse. |
### Usage
```javascript
group.addShape('ellipse', {
attrs: {
x: 100,
y: 100,
rx: 50,
ry: 50,
fill: 'blue'
}
})
```
### Fan
### Special Property
| Name | Description | Remark |
| --- | --- | --- |
| x | The x of the center of the fan. | |
| y | The y of the center of the fan. | |
| rs | The horizontal raidus of the fan. | |
| re | The vertical raidus of the fan. | |
| startAngle | The start angle. | Radian system represented by Math.PI. |
| endAngle | The end angle. | Radian system represented by Math.PI. |
| clockwise | It will be rendered clockwisely if it is `true`, counterclockwisely if it is `false`. | |
### Usage
```javascript
group.addShape('fan', {
attrs: {
x: 50,
y: 50,
re: 40,
rs: 30,
startAngle: 1/2 * Math.PI,
endAngle: Math.PI,
clockwise: false,
fill: '#b7eb8f'
}
})
```
### Image
### Special Property
| Name | Description | Remark |
| --- | --- | --- |
| x | The x of the left top of the image. | |
| y | The y of the left top of the image. | |
| width | The width of the image. | |
| height | The height of the image. | |
| img | The source of the image. | G6 supports multiple image formats: <br />- url<br />- ImageData<br />- Image<br />- canvas<br /> |
### Usage
```javascript
group.addShape('image', {
attrs: {
x: 0,
y: 0,
img:'https://g.alicdn.com/cm-design/arms-trace/1.0.155/styles/armsTrace/images/TAIR.png'
}
})
```
### Marker
### Special Property
| Name | Description | Remark |
| --- | --- | --- |
| x | The x of the center of the marker. | |
| y | The y of the center of the marker. | |
| r | The radius of the marker. | |
| symbol | The shape name. | There are several built-in shapes: `circle`, `square`, `diamond`, `triangle`, `triangle-down`. And user could customize a shape as marker. |
### Usage
```javascript
group.addShape('marker', {
attrs: {
x: 10,
y: 10,
r: 10,
symbol: function(x, y, r) {
return [
[ 'M', x, y ],
[ 'L', x + r, y + r ],
[ 'L'x + r * 2, y ],
[ 'Z' ]
]
}
}
});
```
### Polygon
### Special Property
| Name | Description | Remark |
| --- | --- | --- |
| points | The coordinates of the points on the polygon. | It is an array. |
### Usage
```javascript
group.addShape('polygon', {
attrs: {
points:[[ 30, 30 ], [ 40, 20 ], [ 30, 50 ], [ 60, 100 ]],
fill: 'red'
}
});
```
### Rect
### Special Property
| Name | Description | Remark |
| --- | --- | --- |
| x | The x of left top of the rect. | |
| y | The y of left top of the rect. | |
| width | The width of the rect. | |
| height | The height of the rect. | |
| radius | The border radius. | It can be an integer or an array, representing the border radii of lefttop, righttop, rightbottom, leftbotton respectively. <br />- `radius = 1` or `radius = [ 1 ]` is equal to `radius = [ 1, 1, 1, 1 ]`<br />- `radius = [ 1, 2 ]` is equal to `radius = [ 1, 2, 1, 2 ]`<br />- `radius: [ 1, 2, 3 ]` is equal to `radius: [ 1, 2, 3, 2 ]`<br /> |
### Usage
```javascript
group.addShape('rect', {
attrs: {
x: 150,
y: 150,
width: 150,
height: 150,
stroke: 'black',
radius: [2, 4]
}
});
```
## Path
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>Attention:</strong></span> When the edge is too thin to be hitted by mouse, set **lineAppendWidth** to enlarge the hitting area.
### Special Property
| Name | Description | Remark |
| --- | --- | --- |
| path | The path. | It can be a String, or an Array of path. |
| startArrow | The arrow on the start of the path. | When `startArrow` is `true`, show a default arrow on the start of the path. User can custom an arrow by path. |
| endArrow | The arrow on the end of the path. | When `startArrow` is `true`, show a default arrow on the end of the path. User can custom an arrow by path. |
| lineAppendWidth | The hitting area of the path. | Enlarge the hitting area by enlarging its value. |
| lineCap | The style of two ends of the path. | |
| lineJoin | The style of the intersection of two path. | |
| lineWidth | The line width of the current path. | |
| miterLimit | The maximum miter length. | |
| lineDash | The style of the dash line. | It is an array that describes the length of gaps and line segments. If the number of the elements in the array is odd, the elements will be dulplicated. Such as [5, 15, 25] will be regarded as [5, 15, 25, 5, 15, 25]. |
### Usage
```javascript
group.addShape('path', {
attrs: {
startArrow: {
// The custom arrow is a path centered at (0, 0), and points to the positive direction of x-axis
path: 'M 10,0 L -10,-10 L -10,10 Z',
d: 10
},
endArrow: {
// The custom arrow is a path centered at (0, 0), and points to the positive direction of x-axis
path: 'M 10,0 L -10,-10 L -10,10 Z',
d: 10
},
path: [
[ 'M', 100, 100 ],
[ 'L', 200, 200 ]
],
stroke: '#000',
lineWidth: 8,
lineAppendWidth: 5
}
});
```
## Text
### Properties
| Name | Description | Remark |
| --- | --- | --- |
| fill | The color or gradient color for filling. | The corresponding property in Canvas is `fillStyle`. |
| stroke | The color, gradient color, or pattern for stroke. | The corresponding property in Canvas is `strokeStyle`. |
| shadowColor | The color for shadow. | |
| shadowBlur | The blur level for shadow. | Larger the value, more blur. |
| shadowOffsetX | The horizontal offset of the shadow. | |
| shadowOffsetY | The vertical offset of the shadow. | |
| opacity | The opacity (alpha value) of the shape. | The corresponding property in Canvas is `globalAlpha`. |
| font | The font of the text. | |
| textAlign | The align way of the text. | Options: `'center'` / `'end'` / `'left'` / `'right'` / `'start'`. `'start'` by default. |
| textBaseline | The base line of the text. | Options: <br />`'top'` / `'middle'` / `'bottom'` / `'alphabetic'` / `'hanging'`. `'bottom'` by default. |
| fontStyle | The font style of the text. | The corresponding property in CSS is `font-style` |
| fontVariant | The font variant of the text. | The corresponding property in CSS is `font-variant` |
| fontWeight | The font weight of the text. | The corresponding property in CSS is `font-weight` |
| fontSize | The font size of the text. | The corresponding property in CSS is `font-size` |
| fontFamily | The font family of the text. | The corresponding property in CSS is `font-family` |
| autoRotate | Wheter rotate the text according to the edge automatically if it is a label of an edge. | |
### Usage
```javascript
group.addShape('text', {
attrs: {
text: 'test text',
fill: 'red',
fontWeight: 400,
shadowOffsetX: 10,
shadowOffsetY: 10,
shadowColor: 'blue',
shadowBlur: 10
}
});
```

View File

@ -1,34 +1,37 @@
---
title: 关键概念-图形 Shape 及其属性
order: 0
title: 各图形属性
order: 4
---
G6 中的元素(节点/边)是**由一个或多个小**[**图形 Shape**](https://www.yuque.com/antv/g6/shape-crycle)**组成**,主要通过自定义节点或自定义边时在 `draw` 方法中使用 `group.addShape` 添加G6 中支持以下的图形 Shape
图形是组成图上一个元素(节点/边)的基本单位。节点/边的 `style` 属性即对应了各自 keyShape关键图形的图形属性。节点或边上标签 `labelCfg` 中的 `style` 属性对应了 text 图形的图形属性。
- circle
- rect矩形
- ellipse椭圆
- image图片
- text文本的属性请参考[这里](https://www.yuque.com/antv/g6/gs4gno)
- fan扇形
- marker标记
- polygon多边形
- path路径。
G6 支持以下图形:
- [circle](#圆图形-circle):圆;
- [rect](#矩形图形-rect):矩形;
- [ellipse](#椭圆图形-ellipse):椭圆;
- [polygon](#多边形图形-polygon):多边形;
- [fan](#扇形图形-fan):扇形;
- [image](#图片图形-image):图片;
- [marker](#标记图形-marker):标记;
- [path](#路径-path):路径;
- [text](#文本-text):文本。
## 各图形 Shape 的通用属性
## 通用属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| fill | 设置用于填充绘画的颜色、渐变或模式 | 对应 canvas 属性 `fillStyle` |
| stroke | 设置用于笔触的颜色、渐变或模式 | 对应 canvas 属性 `strokeStyle` |
| fill | 设置用于填充绘画的颜色、渐变或模式 | 对应 Canvas 属性 `fillStyle` |
| stroke | 设置用于笔触的颜色、渐变或模式 | 对应 Canvas 属性 `strokeStyle` |
| lineWidth | 描边宽度 | |
| shadowColor | 设置用于阴影的颜色 | |
| shadowBlur | 设置用于阴影的模糊级别 | 数值越大,越模糊 |
| shadowOffsetX | 设置阴影距形状的水平距离 | |
| shadowOffsetY | 设置阴影距形状的垂直距离 | |
| opacity | 设置绘图的当前 alpha 或透明值 | 对应 canvas 属性 `globalAlpha` |
| opacity | 设置绘图的当前 alpha 或透明值 | 对应 Canvas 属性 `globalAlpha` |
| fillOpacity | 设置填充的 alpha 或透明值 | |
### 用法
## 用法
```javascript
group.addShape('rect', {
attrs: {
@ -43,12 +46,14 @@ group.addShape('rect', {
```
## 圆图形 Circle
### 属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| x | 圆心的 x 坐标 | |
| y | 圆心的 y 坐标 | |
| r | 圆的半径 | |
### 特殊属性
| 属性名 | 含义 |
| --- | --- |
| x | 圆心的 x 坐标 |
| y | 圆心的 y 坐标 |
| r | 圆的半径 |
### 用法
@ -64,15 +69,18 @@ group.addShape('circle', {
```
## 椭圆图形 Ellipse
### 属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| x | 圆心的 x 坐标 | |
| y | 圆心的 y 坐标 | |
| rx | 水平半径 | |
| ry | 垂直半径 | |
### 特殊属性
| 属性名 | 含义 |
| --- | --- |
| x | 圆心的 x 坐标 |
| y | 圆心的 y 坐标 |
| rx | 水平半径 |
| ry | 垂直半径 |
### 用法
```javascript
group.addShape('ellipse', {
@ -86,19 +94,23 @@ group.addShape('ellipse', {
})
```
## 扇形图形 Fan
### 属性
### 特殊属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| x | 扇形圆心的 x 坐标 | |
| y | 扇形圆心的 y 坐标 | |
| rs | 水平半径 | |
| re | 垂直半径 | |
| startAngle | 起点弧度 | 弧度是弧度,即使用 Math.PI 表示 |
| endAngle | 终点弧度 | |
| startAngle | 起点弧度 | 弧度,即使用 Math.PI 表示 |
| endAngle | 终点弧度 | 弧度制,即使用 Math.PI 表示 |
| clockwise | 为 `true` 时顺时针渲染,为 `false` 时逆时针渲染 | |
### 用法
```javascript
group.addShape('fan', {
@ -115,15 +127,19 @@ group.addShape('fan', {
})
```
## 图片图形 Image
### 属性
### 特殊属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| x | 图片左上角的 x 坐标 | |
| y | 图片左上角的 y 坐标 | |
| width | 图片宽度 | |
| height | 图片高度 | |
| img | 图片源 | G6 支持多种格式的图片url、ImageData、Image、canvas |
| img | 图片源 | G6 支持多种格式的图片:<br />- url<br />- ImageData<br />- Image<br />- canvas<br /> |
### 用法
@ -137,14 +153,18 @@ group.addShape('image', {
})
```
## 标记图形 Marker
### 属性
### 特殊属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| x | 中心的 x 坐标 | |
| y | 中心的 y 坐标 | |
| r | 形状半径 | |
| symbol | 指定形状 | 内置了一些常用形状,如圆形 `circle` 矩形 `square` 菱形 `diamond` ,三角形 `triangle` 倒三角形 `triangle-down` ,也可以是自定义的 path 路径。 |
| symbol | 指定形状 | 内置了一些常用形状,如圆形 `circle`,矩形 `square`,菱形 `diamond`,三角形 `triangle`,倒三角形 `triangle-down`,也可以是自定义的 path 路径。 |
### 用法
@ -158,7 +178,7 @@ group.addShape('marker', {
return [
[ 'M', x, y ],
[ 'L', x + r, y + r ],
[ 'L', x + r * 2, y ],
[ 'L'x + r * 2, y ],
[ 'Z' ]
]
}
@ -166,13 +186,17 @@ group.addShape('marker', {
});
```
## 多边形图形 Polygon
### 属性
### 特殊属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| points | 多边形的所有端点坐标 | 数组形式 |
### 用法
```javascript
group.addShape('polygon', {
@ -183,17 +207,21 @@ group.addShape('polygon', {
});
```
## 矩形图形 Rect
### 属性
### 特殊属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| x | 矩形左上角的 x 坐标 | |
| y | 矩形左上角的 y 坐标 | |
| width | 矩形的宽度 | |
| height | 矩形的高度 | |
| radius | 定义圆角 | 支持整数或数组形式, 分别对应左上、右上、右下、左下角的半径:<br />- radius 缩写为 1 或 [ 1 ] 相当于 [ 1, 1, 1, 1 ]<br />- radius 缩写为 [ 1, 2 ] 相当于 [ 1, 2, 1, 2 ]<br />- radius 缩写为 [ 1, 2, 3 ] 相当于 [ 1, 2, 3, 2 ]<br /> |
| radius | 定义圆角 | 支持整数或数组形式,分别对应左上、右上、右下、左下角的半径:<br />- radius 缩写为 1 或 [ 1 ] 相当于 [ 1, 1, 1, 1 ]<br />- radius 缩写为 [ 1, 2 ] 相当于 [ 1, 2, 1, 2 ]<br />- radius 缩写为 [ 1, 2, 3 ] 相当于 [ 1, 2, 3, 2 ]<br /> |
### 用法
```javascript
group.addShape('rect', {
@ -208,10 +236,12 @@ group.addShape('rect', {
});
```
## 路径 Path
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;注意:</span>
边太细时候点击不中,请设置 `lineAppendWidth` 属性值。
### 属性
## 线条 Path
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>⚠️注意:</strong></span>当边太细时候点击不中时,请设置 **lineAppendWidth** 属性值。
### 特殊属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| path | 线条路径 | 可以是 String 形式,也可以是线段的数组。 |
@ -230,11 +260,11 @@ group.addShape('rect', {
group.addShape('path', {
attrs: {
startArrow: {
path: 'M 10,0 L -10,-10 L -10,10 Z', // 自定义箭头为中心点在(0, 0),指向 x 轴正方向的path
path: 'M 10,0 L -10,-10 L -10,10 Z', // 自定义箭头为中心点在(0, 0),指向 x 轴正方向的 path
d: 10
},
endArrow: {
path: 'M 10,0 L -10,-10 L -10,10 Z', // 自定义箭头为中心点在(0, 0),指向 x 轴正方向的path
path: 'M 10,0 L -10,-10 L -10,10 Z', // 自定义箭头为中心点在(0, 0),指向 x 轴正方向的 path
d: 10
},
path: [
@ -249,4 +279,39 @@ group.addShape('path', {
```
## 文本 Text
### 特殊属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| fill | 设置用于填充绘画的颜色、渐变或模式 | 对应 Canvas 属性 `fillStyle` |
| stroke | 设置用于笔触的颜色、渐变或模式 | 对应 Canvas 属性 `strokeStyle` |
| shadowColor | 设置用于阴影的颜色 | |
| shadowBlur | 设置用于阴影的模糊级别 | 数值越大,越模糊 |
| shadowOffsetX | 设置阴影距形状的水平距离 | |
| shadowOffsetY | 设置阴影距形状的垂直距离 | |
| opacity | 设置绘图的当前 alpha 或透明值 | 对应 Canvas 属性 `globalAlpha` |
| font | 设置文本内容的当前字体属性 | |
| textAlign | 设置文本内容的当前对齐方式 | 支持的属性:`center` / `end` / `left` / `right` / `start`,默认值为 `start` |
| textBaseline | 设置在绘制文本时使用的当前文本基线 | 支持的属性:<br />`top` / `middle` / `bottom` / `alphabetic` / `hanging`。默认值为 `bottom` |
| fontStyle | 字体样式 | 对应 `font-style` |
| fontVariant | 设置为小型大写字母字体 | 对应 `font-variant` |
| fontWeight | 字体粗细 | 对应 `font-weight` |
| fontSize | 字体大小 | 对应 `font-size` |
| fontFamily | 字体系列 | 对应 `font-family` |
### 用法
```javascript
group.addShape('text', {
attrs: {
text: 'test text',
fill: 'red',
fontWeight: 400,
shadowOffsetX: 10,
shadowOffsetY: 10,
shadowColor: 'blue',
shadowBlur: 10
}
});
```

View File

@ -1,14 +1,14 @@
---
title: Build 报错
title: Building Error
order: 5
---
### 问题
使用最新版 G6build 时候报如下错误:
## Problem
You might meet the error while building your project with lastest version G6:
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*kNGtS6GiOHUAAAAAAAAAAABkARQnAQ' width=500 />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Y_MvRrVfU4kAAAAAAAAAAABkARQnAQ' width=500 />
### 解决方案
参考[#issues 960](https://github.com/antvis/G6/issues/960)。
## Solution
Refer to <a href='https://github.com/antvis/G6/issues/960' target='_blank'>#issues 960</a>.

View File

@ -3,12 +3,12 @@ title: Build 报错
order: 5
---
### 问题
## 问题
使用最新版 G6build 时候报如下错误:
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*kNGtS6GiOHUAAAAAAAAAAABkARQnAQ' width=500 />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Y_MvRrVfU4kAAAAAAAAAAABkARQnAQ' width=500 />
### 解决方案
参考[#issues 960](https://github.com/antvis/G6/issues/960)
## 解决方案
参考 <a href='https://github.com/antvis/G6/issues/960' target='_blank'>#issues 960</a>

View File

@ -1,33 +1,39 @@
---
title: 如何设置 Edge 前置
title: Render the Edge on the Top
order: 6
---
### 问题
G6 3.x 中如何设置让 Edge 前置,即让 Edge 显示到最上面。
## Problem
How to render the edges on the top of nodes in G6 3.x?
### 解决方案
G6 3.x中 edg e默认是在 node 的下面,所有 node 都在 nodeGroup 中,所有 edge 都在 edgeGroup 中,要改层级的话可以通过修改 group 的层级来实现:
```
## Solution
In G6 3.x, nodes are rendered on the top of edges by default. All the nodes are grouped by a [Graphics Group](/en/docs/manual/advanced/keyconcept/graphics-group) named `nodeGroup`, and all the edges are grouped by another [Graphics Group](/en/docs/manual/advanced/keyconcept/graphics-group) named `edgeGroup`. You can modify the visual levels of the groups to change the visual levels of all nodes and all edges. After changing the visual levels, do remember to call `graph.paint()` to repaint the graph.
```javascript
document.getElementById('changeView').addEventListener('click', (evt) => {
const edge=graph.findById('edge1')
const edgeGroup = graph.get('edgeGroup')
edgeGroup.toFront()
graph.paint()
const edgeGroup = graph.get('edgeGroup'); // Get the defuall group of edges
edgeGroup.toFront(); // Move up the edge group
graph.paint(); // Must be called to repaint the graph
})
```
如果只想让单条边前置,可以这样:
If you want to move up a single edge, please follow the steps:
1. Configure `groupByTypes: false` when instantiating a Graph to turnoff grouping by items' type. The visual levels of the items will correnspond to the generation order of them.
2. Call `toFront()` and `toBack()` to adjust the visual level of single item.
3. Call `graph.paint()` to repaint the graph after level adjustment.
```
```javascript
const graph = new G6.Graph({
// ... Other configurations for graph
groupByTypes: false // Turnoff grouping by items' type
});
document.getElementById('changeView').addEventListener('click', (evt) => {
const edge=graph.findById('edge1')
const nodeGroup = graph.get('nodeGroup')
const edge1Group = edge.get('group')
edge1Group.toFront()
nodeGroup.toBack();
graph.paint()
const edge = graph.findById('edge1'); // Find an edge according to the id
const node = graph.findById('node1'); // Find a node according to the id
edge.toFront(); // Move up the edge
node.toBack(); // Move back the node
graph.paint(); // Must be called to repaint the graph
})
```
详见[#issues 817](https://github.com/antvis/G6/issues/817)。
Refer to <a href='https://github.com/antvis/G6/issues/817' target='_blank'>#issues 817</a> for detail.

View File

@ -3,31 +3,34 @@ title: 如何设置 Edge 前置
order: 6
---
### 问题
## 问题
G6 3.x 中如何设置让 Edge 前置,即让 Edge 显示到最上面。
### 解决方案
G6 3.x中 edg e默认是在 node 的下面,所有 node 都在 nodeGroup 中,所有 edge 都在 edgeGroup 中,要改层级的话可以通过修改 group 的层级来实现:
```
## 解决方案
G6 3.x 中 edge 默认是在 node 的下面,所有 node 属于一个名为 `nodeGroup` 的[图形分组](/zh/docs/manual/advanced/keyconcept/graphics-group),所有 edge 属于名为 `edgeGroup` 的[图形分组](/zh/docs/manual/advanced/keyconcept/graphics-group)。可以通过修改图形分组的层级以改变全体节点与全体边的层级。在改变层级后,必须调用 `graph.paint()` 以重新绘制图。
```javascript
document.getElementById('changeView').addEventListener('click', (evt) => {
const edge=graph.findById('edge1')
const edgeGroup = graph.get('edgeGroup')
edgeGroup.toFront()
graph.paint()
const edgeGroup = graph.get('edgeGroup'); // 得到默认的边图形分组
edgeGroup.toFront(); // 将边图形分组前置
graph.paint(); // 必须调用以重绘
})
```
如果只想让单条边前置,可以这样:
如果只想让单条边前置,首先需要在实例化图时通过 `groupByTypes: false` 关闭按照元素类型分组,此时,节点和边的绘制顺序与它们的生成顺序相关。然后,在需要改变层级的地方使用 `toFront()``toBack()` 调整每个元素的层级。在改变层级后,必须调用 `graph.paint()` 以重新绘制图。
```
```javascript
const graph = new G6.Graph({
// ... 其他实例化图的配置项
groupByTypes: false // 关闭按照元素类型进行分组
});
document.getElementById('changeView').addEventListener('click', (evt) => {
const edge=graph.findById('edge1')
const nodeGroup = graph.get('nodeGroup')
const edge1Group = edge.get('group')
edge1Group.toFront()
nodeGroup.toBack();
graph.paint()
const edge = graph.findById('edge1'); // 根据边的 id 查找边实例
const node = graph.findById('node1'); // 根据节点的 id 查找节点实例
edge.toFront(); // 将该边放置在所有图形的最前面
node.toBack(); // 将该节点放置在所有图形的最后面
graph.paint(); // 必须调用以重绘
})
```
详见[#issues 817](https://github.com/antvis/G6/issues/817)
详见 <a href='https://github.com/antvis/G6/issues/817' target='_blank'>#issues 817</a>

View File

@ -1,9 +1,10 @@
---
title: 使用 G6 让两个节点之间连多条边
title: Multiple Edges between Two Nodes
order: 4
---
有如下的一份数据,如何使用 [G6](https://github.com/antvis/g6) 让两个节点之间连多条边?
## Problem
For such a data below, how to link two nodes with multiple edges?
```javascript
const data = {
@ -31,7 +32,7 @@ const data = {
```
接到上面这个问题后,我们马上就开始动手,二话不说先撸出了下面这段代码。
The following code handles the graph easily:
```javascript
const graph = new G6.Graph({
@ -61,14 +62,14 @@ graph.data(data);
graph.render();
```
So Easy!
The result:
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*9u0BTpCAn-4AAAAAAAAAAABkARQnAQ' width=345 />
如果两个节点之间需要显示3条、4条甚至更多条边该怎么做呢
But what if we want to show 3 or more edges?
我们把数据改成下面这样试试:
We use the data below for example:
```javascript
const data = {
@ -99,22 +100,22 @@ const data = {
};
```
结果发现并不对。
We found that the code above can not handle this situation any more. The result:
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*9u0BTpCAn-4AAAAAAAAAAABkARQnAQ' width=345 />
这个时候,就需要借助 G6 的「自定义边」功能了。
## Solution
有了这个黑科技,什么样的需求,那还不是分分钟的事。
To solve this problem, we utlize the [Custom Edge](/en/docs/manual/advanced/custom-edge) of G6.
当然了,在使用「自定义边」的之前,有两件事还是需要明确下的:
There are two tips should be taken into consideration before customize an edge:
- **两个节点之间同方向超过一条边的,总需要有个标识来区分;**
- **需要有一个值控制边的弯曲度,以防边重叠**。
- **We need a flag to identify whether there are more than one edges with same direction between two nodes**;
- **We need a value to control the curvature of each edge to prevent overlapping**.
我们就在边数据中添加一个 edgeType 用于区分不同的边。有了这个约定以后,就可以开始动手撸码了。
Therefore, we add a property `edgeType` for each edge in its data to identify different types of edges.
完善的自定义边的代码如下所示。
The complete the code for the demo is shown below:
<iframe
src="https://codesandbox.io/embed/restless-breeze-fhief?fontsize=14&hidenavigation=1&theme=dark"
@ -124,4 +125,4 @@ const data = {
sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
></iframe>
到这里为止,我们也就实现了让两个节点之间展示多条边的功能。
Now, the prolem is solved.

View File

@ -1,9 +1,10 @@
---
title: 使用 G6 让两个节点之间连多条边
title: 两节点间存在多条边
order: 4
---
有如下的一份数据,如何使用 [G6](https://github.com/antvis/g6) 让两个节点之间连多条边?
## 问题
有如下的一份数据,如何使用 <a href='https://github.com/antvis/g6' target=''>G6</a> 让两个节点之间连多条边?
```javascript
const data = {
@ -66,7 +67,7 @@ So Easy!
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*9u0BTpCAn-4AAAAAAAAAAABkARQnAQ' width=345 />
如果两个节点之间需要显示3条、4条甚至更多条边该怎么做呢
如果两个节点之间需要显示 3 条、4 条甚至更多条边,该怎么做呢?
我们把数据改成下面这样试试:
@ -103,18 +104,20 @@ const data = {
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*9u0BTpCAn-4AAAAAAAAAAABkARQnAQ' width=345 />
这个时候,就需要借助 G6 的「自定义边」功能了。
## 解决方案
这个时候,需要借助 G6 的 [自定义边](/zh/docs/manual/advanced/custom-edge) 功能。
有了这个黑科技,什么样的需求,那还不是分分钟的事。
当然了,在使用「自定义边」的之前,有两件事还是需要明确下的
在使用「自定义边」前,需要明确两件事
- **两个节点之间同方向超过一条边的,总需要有个标识来区分;**
- **需要有个标识来区分两个节点之间是否超过一条同方向边**
- **需要有一个值控制边的弯曲度,以防边重叠**
我们就在边数据中添加一个 edgeType 用于区分不同的边。有了这个约定以后,就可以开始动手撸码了。
因此,我们在每条边的数据中添加一个 `edgeType` 属性以区分不同的边。有了这个约定以后,就可以开始动手撸码了。
完善的自定义边的代码如下所示
完善的自定义边的代码如下。
<iframe
src="https://codesandbox.io/embed/restless-breeze-fhief?fontsize=14&hidenavigation=1&theme=dark"
@ -124,4 +127,4 @@ const data = {
sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
></iframe>
到这里为止,我们也就实现了让两个节点之间展示多条边的功能。
至此,我们实现了让两个节点之间展示多条边的功能。

View File

@ -3,23 +3,49 @@ title: Use G6 with IE
order: 3
---
最近 [G6 图可视化交流群](/zh/docs/manual/getting-started/#g6-图可视化交流群)里面有同学反馈说 G6 不支持 IE官网上的 Demo 在 IE 上完全打不开,对于这样对问题,我们有考虑过怎么处理,最终没有选择内部处理,具体原因自行脑补。
## Problem
下面针对@vue/cli、umi、create-react-app搭建的项目给出一些解决方案**务必确保在没有引入 G6 时你的项目可以正常运行在IE上**。
Recently, we received some feedbacks about usage of G6 in IE. Some users found there are some display problems when using G6 in IE.
类似如下错误。
## Solution
Import `babel-polyfill` into your project:
- Import `babel-polyfill` in your main entrance file;
- Add some code into `bable-loader`:
```
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('node_modules/@antv/g6')]
}
```
> include indicates the directories of the .js files should to be babel-loader; exclude represents the directories of .js files should not to be babel-loader。
The content of include should be assigned according to your project.
Refer to <a href='https://blog.csdn.net/y491887095/article/details/81541502' target='_blank'>The Link</a> for more detail.
In addition, there are some solutions for the projects with @vue/cli, umi, and create-react-app.
**First, ensure your project can be ran on IE without G6**.
You may find the error:
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*dIrtS6eorxUAAAAAAAAAAABkARQnAQ' width=800 />
## vue/cli
### vue/cli
本[案例](https://github.com/lxfu/vue-g6)是基于@vue/cli(V: 4.0.5)如果你的版本是3.x的话可能写法上会有出入@vue/cli怎么解决依赖兼容性问题呢<br />遇到问题首先想到的是官网,没错,先看看[官网](https://cli.vuejs.org/zh/guide/browser-compatibility.html#polyfill)上有没有类似的教程,从官网上我们定位到浏览器兼容性,如下
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*CuVeQ5k5RloAAAAAAAAAAABkARQnAQ' width=850 />
The <a href='https://github.com/lxfu/vue-g6' target='_blank'>G6 Vue Demo</a> is based on @vue/cli(V: 4.0.5). There will be some small differences to the 3.x version. Now, we are going to solve the compatibility issues of @vue/cli.<br />First, we find the document on <a href='https://cli.vuejs.org/guide/browser-compatibility.html#polyfills' target='_blank'>Vue Official Website</a>, which points out the problem of browser compatibility:
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*J_aTR7CdPnwAAAAAAAAAAABkARQnAQ' width=850 />
从文章中我们貌似已经找到了问题的答案我们需要新建vue.config.js文件和package.json同一目录在里面添加transpileDependencies选项
New a vue.config.js file in the same directory of package.json, and add `transpileDependencies`:
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*EDkTRpk9TxoAAAAAAAAAAABkARQnAQ' width=850 />
该选项默认值是[]说明会忽略掉所有掉node_modules文件不会对node_modules里面对文件做Babel我们需要做的就是把我们希望Babel的文件加入即可代码如下需要注意的是我们加入的依赖**不需要包含node_modules用包名**@antv/g6**)即可**,因为@vue/cli会自动添加前缀node_modules。 还需要注意 @antv/g6必须和package.json里面的一致安装依赖的时候首选npm如果你用yarn、cnpm等安装需要确保node_modules里面的包名没有被更改。
The value of `transpileDependencies` is `[]` by default, which means no Babel with all the node_modules files. Now, we add the files should be Bable into `transpileDependencies` as below. Note that the dependencies to be added **should not contain node_modules, and use the package name @antv/g6**. The reason is that the @vue/cli will add the prefix node_modules automatically. The @antv/g6 must be same consistent to that in package.json. Use npm while installing the dependencies. If you are using yarn or cnpm, you should make sure that there are no modified package name in node_modules.
```javascript
module.exports = {
@ -27,11 +53,11 @@ module.exports = {
};
```
好了我们打开IE11看看结果吧。
Open the project with IE11 to see the result:
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*yS3BRL12vyAAAAAAAAAAAABkARQnAQ' width=850 />
最开始的那个报错解决了但咋出现了新问题呢别急先用chrome浏览器看看发现问题是一样的添加完transpileDependencies兼容性问题是没有了但出了个新错误。再次查看官网并没有相关文章那就直接移步issue吧经过一番查找我们找到如下解决方案在babel.config.js里面添加上sourceType: "unambiguous",具体含有可以官网查阅。
The original error is solved, but new problem shows up. Open the project with Chrome, you can find the same error. The compatibility issue has been solved by adding `transpileDependencies`. We find a solution in the issues of Vue: add `sourceType: "unambiguous"` to babel.config.js, which can be refered to the official website of Vue for the definition.
```javascript
module.exports = {
@ -40,27 +66,17 @@ module.exports = {
};
```
再次编译,
Compile it again:
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*ewAJS55iBOkAAAAAAAAAAABkARQnAQ' width=850 />
到此,完美解决问题。
Now, the prolem is solved.
## create-react-app
### create-react-app
如果你使用create-react-app(V: 3.0.0)初始化项目那么恭喜你create-react-app已经内置了依赖兼容性的处理方案你只需要配置项目自身的兼容性问题即可配置有多种方式可参考[这里]。(https://create-react-app.dev/docs/supported-browsers-features/#configuring-supported-browsers)。<br />
If you are using create-react-app(V: 3.0.0) to initiate your project, create-react-app has built in the solution for compatibility. You only need to configure the compatibility of the project by several methods. Please refer to <a href='https://create-react-app.dev/docs/supported-browsers-features/#configuring-supported-browsers' target='_blank'>HERE</a>.<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*aeWfSKGfgycAAAAAAAAAAABkARQnAQ' width=850 />
当然也许你想看看内部是怎么处理的那就执行npm run eject 或 yarn run eject吧这样就能暴露create-react-app的内置配置了这个操作是不可逆的。 内置配置如下:
If you want to figure out the inner solving process, run `npm run eject` or `yarn run eject` to check the inner configurations of create-react-app. This operation is irreversible.
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*NcvcSL90CvUAAAAAAAAAAABkARQnAQ' width=850 />
## umi
如果你使用的是umi再次恭喜你umi不仅内置了依赖兼容性方案而且配置简单如果有任何问题你可以在答疑群里面@云谦大佬。
```javascript
export default {
browserslist: ['> 1%', 'last 2 versions'],
};
```

View File

@ -3,7 +3,13 @@ title: 如何让 IE 支持 G6
order: 3
---
最近 [G6 图可视化交流群](/zh/docs/manual/getting-started/#g6-图可视化交流群)里面有同学反馈说 G6 不支持 IE。对于这类问题我们在项目中只需要引入 `babel-polyfill` 即可,具体使用方法如下:
## 问题
最近 [G6 图可视化交流群](/zh/docs/manual/introduction/#g6-图可视化交流群) 里有同学反馈 G6 不支持 IE。
## 解决方案
对于这类问题,我们在项目中只需要引入 `babel-polyfill` 即可,具体使用方法如下:
- 在主入门文件中引入 `babel-polyfill`
- 在 `bable-loader` 中加入如下代码:
@ -20,24 +26,25 @@ order: 3
include 中的内容请根据具体项目情况设置。
更详细的请参考https://blog.csdn.net/y491887095/article/details/81541502。
更详细的请参考:<a href='https://blog.csdn.net/y491887095/article/details/81541502' target='_blank'>https://blog.csdn.net/y491887095/article/details/81541502</a>
另外,针对@vue/cli、umi、create-react-app搭建的项目给出一些解决方案**务必确保在没有引入 G6 时你的项目可以正常运行在IE上**。
另外,针对 @vue/cli、umi、create-react-app 搭建的项目给出一些解决方案,**务必确保在没有引入 G6 时你的项目可以正常运行在IE上**。
类似如下错误。
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*dIrtS6eorxUAAAAAAAAAAABkARQnAQ' width=800 />
## vue/cli
### vue/cli
[案例](https://github.com/lxfu/vue-g6)是基于@vue/cli(V: 4.0.5)如果你的版本是3.x的话可能写法上会有出入@vue/cli怎么解决依赖兼容性问题呢<br />遇到问题首先想到的是官网,没错,先看看[官网](https://cli.vuejs.org/zh/guide/browser-compatibility.html#polyfill)上有没有类似的教程,从官网上我们定位到浏览器兼容性,如下
<a href='https://github.com/lxfu/vue-g6' target='_blank'>G6 Vue 案例</a> 是基于 @vue/cli(V: 4.0.5)3.x 版本可能在写法上有些出入。@vue/cli 怎么解决依赖兼容性问题呢?<br />遇到问题首先查看 <a href='https://cli.vuejs.org/zh/guide/browser-compatibility.html#polyfill' target='_blank'>Vue 官网</a> 上有没有类似的教程,从官网上我们定位到浏览器兼容性,如下
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*CuVeQ5k5RloAAAAAAAAAAABkARQnAQ' width=850 />
从文章中我们貌似已经找到了问题的答案我们需要新建vue.config.js文件和package.json同一目录在里面添加transpileDependencies选项
从文章中我们貌似已经找到了问题的答案,我们需要新建 vue.config.js 文件(和 package.json 同一目录),在里面添加 `transpileDependencies` 选项:
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*EDkTRpk9TxoAAAAAAAAAAABkARQnAQ' width=850 />
该选项默认值是[]说明会忽略掉所有掉node_modules文件不会对node_modules里面对文件做Babel我们需要做的就是把我们希望Babel的文件加入即可代码如下需要注意的是我们加入的依赖**不需要包含node_modules用包名**@antv/g6**)即可**,因为@vue/cli会自动添加前缀node_modules。 还需要注意 @antv/g6必须和package.json里面的一致安装依赖的时候首选npm如果你用yarn、cnpm等安装需要确保node_modules里面的包名没有被更改。
该选项默认值是 `[]`,说明会忽略掉所有掉 node_modules 文件,不会对 node_modules 里面对文件做 Babel。我们需要做的就是把我们希望 Babel 的文件加入即可,代码如下。需要注意的是我们加入的依赖**不需要包含 node_modules ,用包名 @antv/g6**即可,因为 @vue/cli 会自动添加前缀 node_modules 。还需要注意 @antv/g6 必须和 package.json 里面的一致。安装依赖的时候首选 npm ,如果你用 yarn、cnpm 等安装,需要确保 node_modules 里面的包名没有被更改。
```javascript
module.exports = {
@ -45,11 +52,11 @@ module.exports = {
};
```
好了我们打开IE11看看结果吧。
好了,我们打开 IE11 看看结果吧。
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*yS3BRL12vyAAAAAAAAAAAABkARQnAQ' width=850 />
最开始的那个报错解决了,但咋出现了新问题呢别急先用chrome浏览器看看发现问题是一样的添加完transpileDependencies兼容性问题是没有了,但出了个新错误。再次查看官网,并没有相关文章,那就直接移步issue吧经过一番查找我们找到如下解决方案在babel.config.js里面添加上sourceType: "unambiguous",具体含有可以官网查阅。
最开始的那个报错解决了,但出现了新问题。先用 Chrome 浏览器看看,发现问题是一样的。添加完 `transpileDependencies` 兼容性问题是没有了,但出了个新错误。再次查看官网,并没有相关文章,那就直接移步 issue 吧。经过一番查找,我们找到如下解决方案,在 babel.config.js 里面添加上 `sourceType: "unambiguous"` ,具体含义可以官网查阅。
```javascript
module.exports = {
@ -58,24 +65,25 @@ module.exports = {
};
```
再次编译,
再次编译:
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*ewAJS55iBOkAAAAAAAAAAABkARQnAQ' width=850 />
到此,完美解决问题。
## create-react-app
### create-react-app
如果你使用create-react-app(V: 3.0.0)初始化项目那么恭喜你create-react-app已经内置了依赖兼容性的处理方案你只需要配置项目自身的兼容性问题即可,配置有多种方式,可参考[这里]。(https://create-react-app.dev/docs/supported-browsers-features/#configuring-supported-browsers)<br />
如果你使用 create-react-app(V: 3.0.0) 初始化项目那么恭喜你create-react-app 已经内置了依赖兼容性的处理方案,你只需要配置项目自身的兼容性问题即可。配置有多种方式,可参考 <a href='https://create-react-app.dev/docs/supported-browsers-features/#configuring-supported-browsers' target='_blank'>这里</a> <br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*aeWfSKGfgycAAAAAAAAAAABkARQnAQ' width=850 />
当然也许你想看看内部是怎么处理的那就执行npm run eject 或 yarn run eject吧这样就能暴露create-react-app的内置配置了这个操作是不可逆的。 内置配置如下:
也许你想看看内部是怎么处理的,可以执行 `npm run eject``yarn run eject` 以暴露 create-react-app 的内置配置。这个操作是不可逆的。内置配置如下:
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*NcvcSL90CvUAAAAAAAAAAABkARQnAQ' width=850 />
## umi
### umi
如果你使用的是umi再次恭喜你umi不仅内置了依赖兼容性方案,而且配置简单,如果有任何问题,你可以在答疑群里面@云谦大佬
umi 不仅内置了依赖兼容性方案,而且配置简单,如果有任何问题,你可以在答疑群里面 @云谦 老师
```javascript
export default {

View File

@ -3,11 +3,11 @@ title: Update Item's Style
order: 1
---
G6 提供了三种修改节点样式的方法。
There are three ways to modify the styles for items in G6.
#### 实例化Graph
#### Configure When Instantiating Graph
实例化 Graph 时,可以通过在 `defaultNode``defaultEdge` 中指定 `**style**` 样式属性。
When instantiating a Graph, assign `style` in `defaultNode` or `defaultEdge` to configure the styles for global nodes and global edges respectively.
```javascript
const graph = new G6.Graph({
@ -31,7 +31,7 @@ const graph = new G6.Graph({
});
```
#### 数据中指定style
#### Configure style in Data
```javascript
const data = {
nodes: [
@ -47,17 +47,15 @@ const data = {
}
```
#### 使用 update / updateItem
使用 `update` / `updateItem` 更新节点或边。
#### update / updateItem
```javascript
graph.updateItem(node, {
// 节点的样式
// The node style
style: {
stroke: 'blue'
}
})
```
想要知道节点都支持哪些属性样式,请👉参数[节点支持的属性](/zh/docs/api/properties/NodeProperties)。
For more information about the styles, refer to [Node Style Properties](/en/docs/manual/middle/elements/nodes/defaultNode/#style).

View File

@ -5,9 +5,9 @@ order: 1
G6 提供了三种修改节点样式的方法。
#### 实例化Graph
#### 实例化 Graph
实例化 Graph 时,可以通过在 `defaultNode``defaultEdge` 中指定 `**style**` 样式属性。
实例化 Graph 时,可以通过在 `defaultNode``defaultEdge` 中指定 `style` 分别配置全局节点和全局边的样式属性。
```javascript
const graph = new G6.Graph({
@ -31,7 +31,7 @@ const graph = new G6.Graph({
});
```
#### 数据中指定style
#### 数据中指定 style
```javascript
const data = {
nodes: [
@ -60,4 +60,4 @@ graph.updateItem(node, {
})
```
想要知道节点都支持哪些属性样式,请👉参数[节点支持的属性](/zh/docs/api/properties/NodeProperties)。
想要知道节点都支持哪些属性样式,请参考 [节点样式属性](/zh/docs/manual/middle/elements/nodes/defaultNode/#样式属性-style)。

View File

@ -3,10 +3,11 @@ title: Update Label
order: 0
---
在 G6 中,可以通过以下三种方式更新文本样式。
There are three ways to modify the styles for labels in G6.
#### Configure When Instantiating Graph
When instantiating a Graph, assign `labelCfg` in `defaultNode` or `defaultEdge` to configure the styles for labels of global nodes and global edges respectively.
#### 实例化Graph
实例化Graph时可以通过在defaultNode或defaultEdge中指定**labelCfg**属性修改文本的样式。
```javascript
const graph = new G6.Graph({
@ -34,7 +35,7 @@ const graph = new G6.Graph({
});
```
#### 数据中指定labelCfg
#### Configure Style in Data
```javascript
const data = {
@ -53,17 +54,17 @@ const data = {
}
```
#### 使用update/updateItem
#### update/updateItem
使用update/updateItem更新节点或边时也可以更新节点或边上的文本。
When using `update/updateItem` to update a node or edge, the label can be updated as well.
```javascript
graph.updateItem(node, {
// 节点的样式
// The style of the node
style: {
stroke: 'blue'
},
// 节点上文本的样式
// The configurations of the label on the node
labelCfg: {
style: {
fill: '#fff',
@ -73,4 +74,4 @@ graph.updateItem(node, {
})
```
想知道文本都可以设置哪些属性,请👉参考[文本属性样式](/zh/docs/api/properties/TextProperties)。
For more information about the label styles, refer to [Label on Node](/en/docs/manual/middle/elements/nodes/defaultNode/#label-and-labelcfg) and [Label on Edge](/en/docs/manual/middle/elements/edges/defaultEdge/#label-and-labelcfg).

View File

@ -5,8 +5,8 @@ order: 0
在 G6 中,可以通过以下三种方式更新文本样式。
#### 实例化Graph
实例化Graph时可以通过在defaultNode或defaultEdge中指定**labelCfg**属性修改文本的样式。
#### 实例化 Graph
实例化 Graph 时,可以通过在 `defaultNode``defaultEdge` 中指定 `labelCfg` 属性修改文本的样式。
```javascript
const graph = new G6.Graph({
@ -34,7 +34,7 @@ const graph = new G6.Graph({
});
```
#### 数据中指定labelCfg
#### 数据中指定 labelCfg
```javascript
const data = {
@ -53,9 +53,9 @@ const data = {
}
```
#### 使用update/updateItem
#### 使用 update/updateItem
使用update/updateItem更新节点或边时也可以更新节点或边上的文本。
使用 `update/updateItem` 更新节点或边时,也可以更新节点或边上的文本。
```javascript
graph.updateItem(node, {
@ -73,4 +73,4 @@ graph.updateItem(node, {
})
```
想知道文本都可以设置哪些属性,请👉参考[文本属性样式](/zh/docs/api/properties/TextProperties)。
想知道文本都可以设置哪些属性,请参考 [节点上的文本属性](/zh/docs/manual/middle/elements/nodes/defaultNode/#标签文本-label-及其配置-labelcfg) 或 [边上的文本属性](/zh/docs/manual/middle/elements/edges/defaultEdge/#标签文本-label-及其配置-labelcfg)。

View File

@ -1,47 +1,48 @@
---
title: 基础动画
title: Basic Animation
order: 8
---
G6 中的动画分为两个层次:
There are two-level animations in G6:
- 全局动画:全局性的动画,图整体变化时的动画过渡;
- 元素(边和节点)动画:节点或边上的独立动画。
- GLobal animation: Transform the graph animatively when the changes are global;
- Item animation: The animation on a node or an edge.
<br />
## 全局动画
G6 的全局动画指通过图实例进行某些全局操作时,产生的动画效果。例如:
## Global Animation
The global animation is controlled by Graph instance. It takes effect when some global changes happen, such as:
- `graph.updateLayout(cfg)` 布局的变化
- `graph.changeData()` 数据的变化
- `graph.updateLayout(cfg)` change the layout;
- `graph.changeData()` change the data.
通过实例化图时配置 `animate: true`,可以达到每次进行上述操作时,动画效果变化的目的。配合 `animateCfg` 配置动画参数:<br />
Configure `animate: true` when instantiating a graph to achieve it.
<br />
```javascript
const graph = new G6.Graph({
// ... // 图的其他配置项
animate: true, // Boolean,切换布局时是否使用动画过度,默认为 false
// ... // Other configurations
animate: true, // Boolean, whether to activate the animation when global changes happen
animateCfg: {
duration: 500, // Number,一次动画的时长
easing: 'linearEasing' // String,动画函数,可选项:''
duration: 500, // Number, the duration of one animation
easing: 'linearEasing' // String, the easing function
}
});
```
### easing 函数
easing 函数是指动画的函数。例如线性插值、先快后慢等。<br />G6 支持所有 d3 中的动画函数。因此,上面代码中 `animateCfg` 配置中的 String 类型的 `easing` 可以取值有:<br />`'easeLinear'` <br />`'easePolyIn'` `'easePolyOut'` `'easePolyInOut'` <br />`'``easeQuad``'` `'easeQuadIn'` `'easeQuadOut'`  `'easeQuadInOut'`
G6 supports all the easing functions in d3.js. Thus, the options of `easing` in `animateCfg`: <br />`'easeLinear'`, <br />`'easePolyIn'`, `'easePolyOut'`, `'easePolyInOut'` , <br />`'``easeQuad``'`, `'easeQuadIn'`, `'easeQuadOut'`, `'easeQuadInOut'` .
更多取值及所有取值含义参见:[d3 Easings](https://github.com/d3/d3/blob/master/API.md#easings-d3-ease)。
For more detail of the easing functions, please refer to: <a href='https://github.com/d3/d3/blob/master/API.md#easings-d3-ease' target='_blank'>d3 Easings</a>.
## 元素动画
由于 G6 的内置节点和边是没有动画的,需要实现节点和边上的动画需要通过[自定义节点](/zh/docs/manual/advanced/custom-node)、[自定义边](/zh/docs/manual/advanced/custom-edge)时复写 `afterDraw` 实现。
## Item Animation
All the built-in nodes and edges are static withou animation. To animate node or edge, please register your type of [Custom Node](/en/docs/manual/advanced/custom-node) or [Custom Edge](/en/docs/manual/advanced/custom-edge), and rewrite the `afterDraw` function.
### 节点动画
关于节点动画,以下面三个动画示例进行讲解:
### Node Animation
The animation frames are applied on one graphics shape of a node.
We are going to introduce this part by three demos:
- 节点上图形的动画(如下图左);
- 增加带有动画的背景图形(如下图中);
- 节点上部分图形的旋转动画(如下图右)。
- The graphics animation (Left of the figure below);
- The background animation (Center of the figure below);
- Partial animation (Right of the figure below).
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*aAjWQ4n_OOEAAAAAAAAAAABkARQnAQ' alt='download' width='150'/>
@ -49,45 +50,44 @@ easing 函数是指动画的函数。例如线性插值、先快后慢等。<br
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*uFQsQqxIa_QAAAAAAAAAAABkARQnAQ' alt='download' width='150'/>
<br />
以上三个动画节点的 demo 代码见:
[节点动画](https://codepen.io/Yanyan-Wang/pen/QWWEEWe)。
The code of the three demos can be found at:
<a href='/en/examples/scatter/node' target='_blank'>Node Animation</a>.
#### 节点上图形的动画
节点上的动画,即每一帧发生变化的是节点上的某一个图形。<br />
#### The Graphics Animation
In this example, we are going to magnify and shrink the node. <br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*aAjWQ4n_OOEAAAAAAAAAAABkARQnAQ' alt='download' width='150'/>
本例实现节点放大缩小,通过 `group.get('children')[0]` 找到需要更新的图形(这里找到该节点上第 0 个图形),然后调用该图形的 `animate` 方法指定动画的参数及每一帧的变化( `onFrame` 方法返回每一帧需要变化的参数集)。
We first find the graphics shape to be animated by `group.get('children')[0]`. Here we find the 0th graphics shape of this type of node. Then, we call `animate` for the node to define the properties for each frame(The first parameter is a function which returns the properties of each frame, the second parameter defines the configuration for animation).
```javascript
// 放大、变小动画
// Magnify and shrink animation
G6.registerNode('circle-animate', {
afterDraw(cfg, group) {
// 获取该节点上的第一个图形
// Get the first graphics shape of this type of node
const shape = group.get('children')[0];
// 该图形的动画
shape.animate({
// 动画重复
repeat: true,
// 每一帧的操作,入参 ratio这一帧的比例值Number。返回值这一帧需要变化的参数集Object
onFrame(ratio) {
// 先变大、再变小
const diff = ratio <=0.5 ? ratio * 10 : (1 - ratio) * 10;
let radius = cfg.size;
if (isNaN(radius)) radius = radius[0];
// 返回这一帧需要变化的参数集,这里只包含了半径
return {
r: radius / 2 + diff
}
// The animation
shape.animate((ratio) => {// Returns the properties for each frame. The input parameter ratio is a number that range from 0 to 1. The return value is an object that defines the properties for this frame.
// Magnify first, and then shrink
const diff = ratio <=0.5 ? ratio * 10 : (1 - ratio) * 10;
let radius = cfg.size;
if (isNaN(radius)) radius = radius[0];
// The properties for this frame. Only radius for this example
return {
r: radius / 2 + diff
}
}, 3000, 'easeCubic'); // 一次动画持续的时长为 3000动画效果为 'easeCubic'
}, {
repeat: true, // Whehter play the animation repeatly
duration: 3000, // The duration of one animation is 3000
easing: 'easeCubic' // The easing fuction is 'easeCubic'
});
}
}, 'circle'); // 该自定义节点继承了内置节点 'circle',除了被复写的 afterDraw 方法外,其他按照 'circle' 里的函数执行。
}, 'circle'); // This custom node extend the built-in node 'circle'. Except for the rewrited afterDraw, other functions will extend from 'circle' node
```
#### 增加带有动画的背景图形
`afterDraw` 方法中为已有节点添加额外的 shape ,并为这些新增的图形设置动画。<br />
#### Background Animation
You can add extra shape with animation in `afterDraw`.<br />
本例在 `afterDraw` 方法中,绘制了三个背景 circle ,分别使用不同的颜色填充,再调用 `animate` 方法实现这三个 circle 逐渐变大、变淡的动画。本例中没有使用 `onFrame` 函数,直接在 `animate` 函数的入参中设置每次动画结束时的最终目标样式,即半径增大 10透明度降为 0.1。<br />
In `afterDraw` of this demo, we draw three background circle shape with different filling colors. And the `animate` is called for magnifying and fading out the three circles. We do not use set the first parameter as a function here, but assign the target style for each animation to the input paramter: magify the radius to 10 and reduce the opacity to 0.1. The second parameter defines the configuration for the animation.<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*FxDJQ5eY-5oAAAAAAAAAAABkARQnAQ' alt='download' width='150'/>
@ -98,7 +98,7 @@ G6.registerNode('background-animate', {
if (isNaN(r)) {
r = cfg.size[0] / 2;
};
// 第一个背景圆
// The first background circle
const back1 = group.addShape('circle',{
zIndex: -3,
attrs: {
@ -109,18 +109,18 @@ G6.registerNode('background-animate', {
opacity: 0.6
}
});
// 第二个背景圆
// The second background circle
const back2 = group.addShape('circle',{
zIndex: -2,
attrs: {
x: 0,
y: 0,
r,
fill: 'blue', // 为了显示清晰,随意设置了颜色
fill: 'blue',
opacity: 0.6
}
});
// 第三个背景圆
// The third background circle
const back3 = group.addShape('circle',{
zIndex: -1,
attrs: {
@ -131,34 +131,46 @@ G6.registerNode('background-animate', {
opacity: 0.6
}
});
group.sort(); // 排序,根据 zIndex 排序
group.sort(); // Sort the graphic shapes of the nodes by zIndex
// 第一个背景圆逐渐放大,并消失
// Magnify the first circle and fade it out
back1.animate({
r: r + 10,
opacity: 0.1,
repeat: true // 循环
}, 3000, 'easeCubic', null, 0) // 无延迟
opacity: 0.1
}, {
repeat: true, // Play the animation repeatly
duration: 3000,
easing: 'easeCubic'
delay: 0 // No delay
})
// 第二个背景圆逐渐放大,并消失
// Magnify the second circle and fade it out
back2.animate({
r: r + 10,
opacity: 0.1,
repeat: true // 循环
}, 3000, 'easeCubic', null, 1000) // 1 秒延迟
opacity: 0.1
}, {
repeat: true // Play the animation repeatly
duration: 3000,
easing: 'easeCubic',
delay: 1000 // Delay 1s
})
// 第三个背景圆逐渐放大,并消失
// Magnify the third circle and fade it out
back3.animate({
r: r + 10,
opacity: 0.1,
repeat: true // 循环
}, 3000, 'easeCubic', null, 2000) // 2 秒延迟
opacity: 0.1
}, {
repeat: true // Play the animation repeatly
duration: 3000,
easing: 'easeCubic',
delay: 2000 // Delay 2s
})
}
}, 'circle');
```
#### 部分图形旋转动画
这一例也是在 `afterDraw` 方法中为已有节点添加额外的 shape (本例中为 image并为这些新增的图形设置旋转动画。旋转动画较为复杂需要通过矩阵的操作实现。<br />
#### Partial Animation
In this demo, we add extra graphics shape(an image) in `afterDraw`, and set a rotation animation for it. Note that the rotation animation is a little complicated, which should be manipulated by matrix.<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*uFQsQqxIa_QAAAAAAAAAAABkARQnAQ' alt='download' width='150'/>
@ -168,7 +180,7 @@ G6.registerNode('inner-animate', {
const size = cfg.size;
const width = size[0] - 12;
const height = size[1] - 12;
// 添加图片 shape
// Add an image shape
const image = group.addShape('image', {
attrs: {
x: - width / 2,
@ -178,57 +190,56 @@ G6.registerNode('inner-animate', {
img: cfg.img
}
});
// 该图片 shape 的动画
image.animate({
// 动画重复
repeat: true,
// 每一帧的操作,入参 ratio这一帧的比例值Number。返回值这一帧需要变化的参数集Object
onFrame(ratio) {
// 旋转通过矩阵来实现
// 当前矩阵
const matrix = Util.mat3.create();
// 目标矩阵
const toMatrix = Util.transform(matrix, [
['r', ratio * Math.PI * 2]
]) ;
// 返回这一帧需要的参数集,本例中只有目标矩阵
return {
matrix: toMatrix
};
}
}, 3000, 'easeCubic');
// Add animation for the image
image.animate((ratio) => {// Returns the properties for each frame. The input parameter ratio is a number that range from 0 to 1. The return value is an object that defines the properties for this frame.
// Rotate by manipulating matrix
// The current matrix
const matrix = Util.mat3.create();
// The target matrix
const toMatrix = Util.transform(matrix, [
['r', ratio * Math.PI * 2]
]) ;
// The properties of this frame. Only target matrix for this demo
return {
matrix: toMatrix
};
}, {
repeat: true, // Play the animation repeatly
duration: 3000,
easing: 'easeCubic'
});
}
}, 'rect');
```
### 边动画
关于边动画,以下面三个动画示例进行讲解:
### Edge Animation
We are going to introduce this part by three demos:
- 圆点在沿着线运动(下图左);
- 虚线运动的效果下图中gif 图片的帧率问题导致看起来是静态的,可以访问下面的 demo 链接查看);
- 线从无到有的效果(下图右)。
- A circle move along the edge (Left of the figure below);
- A running dashed line (Center of the figure below. The gif may look like a static edge due to the low fps problem. You can check out the demo by link);
- A growing line (Right of the figure below).
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*OAGPRZbYpw4AAAAAAAAAAABkARQnAQ' alt='download' width='150'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*VUgETK6aMzcAAAAAAAAAAABkARQnAQ' alt='download' width='110'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*VUgETK6aMzcAAAAAAAAAAABkARQnAQ' alt='download' width='150'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-l9lQ7Ck1QcAAAAAAAAAAABkARQnAQ' alt='download' width='150'/>
以上三个边动画的 demo 代码见:[边动画](https://codepen.io/Yanyan-Wang/pen/yLLJJoJ)。
The code of the three demo can be found in: <a href='/en/examples/scatter/edge' target='_blank'>Edge Animation</a>.
#### 圆点运动
本例通过在 afterDraw 方法中为边增加了一个 circle 图形,该图形沿着线运动。沿着线运动的原理:设定每一帧中,该 circle 在线上的相对位置。<br />
#### A Moving Circle
In this demo, we add a circle shape with moving animation in `afterDraw`. In each frame, we return the relative position of the circle on the edge.<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*OAGPRZbYpw4AAAAAAAAAAABkARQnAQ' alt='download' width='150'/>
```javascript
G6.registerEdge('circle-running', {
afterDraw(cfg, group) {
// 获得当前边的第一个图形,这里是边本身的 path
// Get the first graphics shape of this type of edge, which is the edge's path
const shape = group.get('children')[0];
// 边 path 的起点位置
// The start point of the edge's path
const startPoint = shape.getPoint(0);
// 添加红色 circle 图形
// Add a red circle shape
const circle = group.addShape('circle', {
attrs: {
x: startPoint.x,
@ -238,33 +249,31 @@ G6.registerEdge('circle-running', {
}
});
// 对红色圆点添加动画
circle.animate({
// 动画重复
repeat: true,
// 每一帧的操作,入参 ratio这一帧的比例值Number。返回值这一帧需要变化的参数集Object
onFrame(ratio) {
// 根据比例值,获得在边 path 上对应比例的位置。
const tmpPoint = shape.getPoint(ratio);
// 返回需要变化的参数集,这里返回了位置 x 和 y
return {
x: tmpPoint.x,
y: tmpPoint.y
};
}
}, 3000); // 一次动画的时间长度
// Add the animation to the red circle
circle.animate((ratio) => {// Returns the properties for each frame. The input parameter ratio is a number that range from 0 to 1. The return value is an object that defines the properties for this frame
// Get the position on the edge according to the ratio
const tmpPoint = shape.getPoint(ratio);
// Return the properties of this frame, x and y for this demo
return {
x: tmpPoint.x,
y: tmpPoint.y
};
}, {
repeat: true, // Play the animation repeatly
duration: 3000, // The duration for one animation
});
}
}, 'cubic'); // 该自定义边继承内置三阶贝塞尔曲线 cubic
}, 'cubic'); // Extend the built-in edge cubic
```
#### 虚线运动的效果
虚线运动的效果是通过计算线的 `lineDash` ,并在每一帧中不断修改实现。<br />
#### Running Dashed Line
The running dashed line is achieved by modifying the `lineDash` in every frame.<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*VUgETK6aMzcAAAAAAAAAAABkARQnAQ' alt='download' width='150'/>
```javascript
// lineDash 的差值,可以在后面提供 util 方法自动计算
// The values of the lineDash. It can be calculated by util
const dashArray = [
[0,1],
[0,2],
@ -278,41 +287,39 @@ const dashArray = [
];
const lineDash = [4, 2, 1, 2];
const interval = 9; // lineDash 的和
const interval = 9; // The total length of the lineDash
G6.registerEdge('line-dash', {
afterDraw(cfg, group) {
// 获得该边的第一个图形,这里是边的 path
// Get the first graphics shape of this type of edge, which is the edge's path
const shape = group.get('children')[0];
// 获得边的 path 的总长度
// The start point of the edge's path
const length = shape.getTotalLength();
let totalArray = [];
// 计算出整条线的 lineDash
// Calculate the lineDash for the whole line
for (var i = 0; i < length; i += interval) {
totalArray = totalArray.concat(lineDash);
}
let index = 0;
// 边 path 图形的动画
shape.animate({
// 动画重复
repeat: true,
// 每一帧的操作,入参 ratio这一帧的比例值Number。返回值这一帧需要变化的参数集Object
onFrame(ratio) {
const cfg = {
lineDash: dashArray[index].concat(totalArray)
};
// 每次移动 1
index = (index + 1) % interval;
// 返回需要修改的参数集,这里只修改了 lineDash
return cfg;
}
}, 3000); // 一次动画的时长为 3000
// Define the animation
shape.animate((ratio) => { // Returns the properties for each frame. The input parameter ratio is a number that range from 0 to 1. The return value is an object that defines the properties for this frame
const cfg = {
lineDash: dashArray[index].concat(totalArray)
};
// Move 1 each frame
index = (index + 1) % interval;
// Return the properties of this frame, lineDash for this demo
return cfg;
}, {
repeat: true, // Play the animation repeatly
duration: 3000, // The duration for one animation
}); // The duration for one animation
}
}, 'cubic'); // 该自定义边继承了内置三阶贝塞尔曲线边 cubic
}, 'cubic'); // Extend the built-in edge cubic
```
#### 线从无到有
线从无到有的动画效果,同样可以通过计算 `lineDash` 来实现。<br />
#### A Growing Edge
A growing edge can also be implemented by calculating the `lineDash`. <br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-l9lQ7Ck1QcAAAAAAAAAAABkARQnAQ' alt='download' width='150'/>
@ -321,37 +328,35 @@ G6.registerEdge('line-growth', {
afterDraw(cfg, group) {
const shape = group.get('children')[0];
const length = group.getTotalLength();
shape.animate({
// 动画重复
repeat: true,
// 每一帧的操作,入参 ratio这一帧的比例值Number。返回值这一帧需要变化的参数集Object
onFrame(ratio) {
shape.animate((ratio) => {// Returns the properties for each frame. The input parameter ratio is a number that range from 0 to 1. The return value is an object that defines the properties for this frame
const startLen = ratio * length;
// 计算线的lineDash
// Calculate the lineDash
const cfg = {
lineDash: [startLen, length - startLen]
};
return cfg;
}
}, 2000); // 一次动画的时长为 2000
}, {
repeat: true, // Play the animation repeatly
duration: 2000, // The duration for one animation
});
}
}, 'cubic'); // 该自定义边继承了内置三阶贝塞尔曲线边 cubic
}, 'cubic'); // Extend the built-in edge cubic
```
### 交互动画
在交互的过程中也可以添加动画。如下图所示,当鼠标移到节点上时,所有与该节点相关联的边都展示虚线运动的动画。<br />![交互动画.gif](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-90pSrm4hkUAAAAAAAAAAABkARQnAQ)<br />上图完整 demo 即代码参见:[状态切换动画](/zh/examples/scatter/stateChange)。
### Interaction Animation
G6 allows user to add animation for the interaction. As showin in the figure beow, when the mouse enters the node, the related edges will show the dashed line animation.<br />![交互动画.gif](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-90pSrm4hkUAAAAAAAAAAABkARQnAQ)<br />The code for the demo can be found in: <a href='/en/examples/scatter/stateChange' target='_blank'>Animation of State Changing</a>.
这种动画涉及到了边的 [状态](/zh/docs/manual/middle/states/state)。在自定义边时复写 `setState` 方法,可对边的各种状态进行监听。鼠标移动到节点上,相关边的某个状态被开启,`setState` 方法中监听到后开启动画效果。步骤如下:
This kind of animation is related to the [State](/en/docs/manual/middle/states/state) of edge. Rewrite the function `setState` to response the state changing. When the mouse enters a node, some state of the related edges are activated. The `setState` of the edges activate the animation once it receive the state changing. The steps are:
- 自定义边中复写 `setState` 方法监听该边的状态,以及某状态下的动画效果;
- 监听中间的节点的 `mouseenter``mouseleave` 事件,触发相关边的状态变化。
- Rewrite the `setState` in custom edge, and listen to the state changing in this function;
- Listen the `mouseenter` and `mouseleave` of the nodes to activate the state of the related edges.
下面代码节选自 demo [状态切换动画](/zh/examples/scatter/stateChange),请注意省略了部分代码,只展示了交互相关以及边动画相关的代码。
The code below is a part of the code in <a href='/en/examples/scatter/stateChange' target='_blank'>Animation of State Changing</a>. Please note that we have omit some code to emphasize the code related to the animation.
```javascript
// const data = ...
// const graph = new G6.Graph({...});
// lineDash 的差值,可以在后面提供 util 方法自动计算
// The values of the lineDash. It can be calculated by util
const dashArray = [
[0,1],
[0,2],
@ -365,16 +370,16 @@ const dashArray = [
];
const lineDash = [4, 2, 1, 2];
const interval = 9; // lineDash 的总长度。
const interval = 9; // The total length of the lineDash
// 注册名为 'can-running' 的边
// Register a type of edge named 'can-running'
G6.registerEdge('can-running', {
// 复写setState方法
// Rewrite setState
setState(name, value, item) {
const shape = item.get('keyShape');
// 监听 running 状态
// Response the running state
if (name === 'running') {
// running 状态为 true 时
// When the running state is turned to be true
if (value) {
const length = shape.getTotalLength();
let totalArray = [];
@ -382,45 +387,43 @@ G6.registerEdge('can-running', {
totalArray = totalArray.concat(lineDash);
}
let index = 0;
shape.animate({
// 动画重复
repeat: true,
// 每一帧的操作,入参 ratio这一帧的比例值Number。返回值这一帧需要变化的参数集Object
onFrame(ratio) {
const cfg = {
lineDash: dashArray[index].concat(totalArray)
};
index = (index + 1) % interval;
return cfg;
}
}, 3000); // 一次动画的时长为 3000
} else { // running 状态为 false 时
// 结束动画
shape.animate((ratio) => { // Returns the properties for each frame. The input parameter ratio is a number that range from 0 to 1. The return value is an object that defines the properties for this frame
const cfg = {
lineDash: dashArray[index].concat(totalArray)
};
index = (index + 1) % interval;
return cfg;
}, {
repeat: true, // Play the animation repeatly
duration: 3000, // The duration for one animation
});
} else { // When the running state is turned to be false
// Stop the animation
shape.stopAnimate();
// 清空 lineDash
// Clear the lineDash
shape.attr('lineDash', null);
}
}
}
}, 'cubic-horizontal'); // 该自定义边继承了内置横向三阶贝塞尔曲线边 cubic-horizontal
}, 'cubic-horizontal'); // Extend the built-in edge cubic-horizontal
// 监听节点的 mouseenter 事件
// Listen the mouseenter event on node
graph.on('node:mouseenter', ev => {
// 获得当前鼠标操作的目标节点
// Get the target node of the event
const node = ev.item;
// 获得目标节点的所有相关边
// Get the related edges of the target node
const edges = node.getEdges();
// 将所有相关边的 running 状态置为 true此时将会触发自定义节点的 setState 函数
// Turn the running state of all the related edges to be true. The setState function will be activated now
edges.forEach(edge => graph.setItemState(edge, 'running', true));
});
// 监听节点的 mouseleave 事件
// Listen the mouseleave event on node
graph.on('node:mouseleave', ev => {
// 获得当前鼠标操作的目标节点
// Get the target node of the event
const node = ev.item;
// 获得目标节点的所有相关边
// Get the related edges of the target node
const edges = node.getEdges();
// 将所有相关边的 running 状态置为 false此时将会触发自定义节点的 setState 函数
// Turn the running state of all the related edges to be false. The setState function will be activated now
edges.forEach(edge => graph.setItemState(edge, 'running', false));
});
@ -428,6 +431,6 @@ graph.on('node:mouseleave', ev => {
// graph.render();
```
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;注意:</span>
running 为 false 时,要停止动画,同时把 lineDash 清空。
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;<strong>Attention:</strong></span>
When `running` is turned to be `false`, the animation should be stopped and the `lineDash` should be cleared.

View File

@ -22,21 +22,22 @@ const graph = new G6.Graph({
animate: true, // Boolean切换布局时是否使用动画过度默认为 false
animateCfg: {
duration: 500, // Number一次动画的时长
easing: 'linearEasing' // String动画函数,可选项:''
easing: 'linearEasing' // String动画函数
}
});
```
### easing 函数
easing 函数是指动画的函数。例如线性插值、先快后慢等。<br />G6 支持所有 d3 中的动画函数。因此,上面代码中 `animateCfg` 配置中的 String 类型的 `easing` 可以取值有:<br />`'easeLinear'` <br />`'easePolyIn'` `'easePolyOut'` `'easePolyInOut'` <br />`'``easeQuad``'` `'easeQuadIn'` `'easeQuadOut'`  `'easeQuadInOut'`
easing 函数是指动画的函数。例如线性插值、先快后慢等。<br />G6 支持所有 d3.js 中的动画函数。因此,上面代码中 `animateCfg` 配置中的 String 类型的 `easing` 可以取值有:<br />`'easeLinear'` <br />`'easePolyIn'` `'easePolyOut'` `'easePolyInOut'` <br />`'``easeQuad``'` `'easeQuadIn'` `'easeQuadOut'`  `'easeQuadInOut'`
更多取值及所有取值含义参见:[d3 Easings](https://github.com/d3/d3/blob/master/API.md#easings-d3-ease)
更多取值及所有取值含义参见:<a href='https://github.com/d3/d3/blob/master/API.md#easings-d3-ease' target='_blank'>d3 Easings</a>
## 元素动画
由于 G6 的内置节点和边是没有动画的,需要实现节点和边上的动画需要通过[自定义节点](/zh/docs/manual/advanced/custom-node)、[自定义边](/zh/docs/manual/advanced/custom-edge)时复写 `afterDraw` 实现。
### 节点动画
节点上的动画,即每一帧发生变化的是节点上的某一个图形。
关于节点动画,以下面三个动画示例进行讲解:
- 节点上图形的动画(如下图左);
@ -50,14 +51,14 @@ easing 函数是指动画的函数。例如线性插值、先快后慢等。<br
<br />
以上三个动画节点的 demo 代码见:
[节点动画](https://codepen.io/Yanyan-Wang/pen/QWWEEWe)
<a href='/zh/examples/scatter/node' target='_blank'>节点动画</a>
#### 节点上图形的动画
节点上的动画,即每一帧发生变化的是节点上的某一个图形。<br />
<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*aAjWQ4n_OOEAAAAAAAAAAABkARQnAQ' alt='download' width='150'/>
本例实现节点放大缩小,通过 `group.get('children')[0]` 找到需要更新的图形(这里找到该节点上第 0 个图形),然后调用该图形的 `animate` 方法指定动画的参数及每一帧的变化( `onFrame` 方法返回每一帧需要变化的参数集)。
本例实现节点放大缩小,通过 `group.get('children')[0]` 找到需要更新的图形(这里找到该节点上第 0 个图形),然后调用该图形的 `animate` 方法指定动画的参数及每一帧的变化( 第一个参数是返回每一帧需要变化的参数集的函数,其参数 `ratio` 是当前正在进行的一次动画的进度,范围 [0, 1],第二个参数是动画的参数)。
```javascript
// 放大、变小动画
G6.registerNode('circle-animate', {
@ -65,21 +66,21 @@ G6.registerNode('circle-animate', {
// 获取该节点上的第一个图形
const shape = group.get('children')[0];
// 该图形的动画
shape.animate({
shape.animate((ratio) => { // 每一帧的操作,入参 ratio这一帧的比例值Number。返回值这一帧需要变化的参数集Object
// 先变大、再变小
const diff = ratio <=0.5 ? ratio * 10 : (1 - ratio) * 10;
let radius = cfg.size;
if (isNaN(radius)) radius = radius[0];
// 返回这一帧需要变化的参数集,这里只包含了半径
return {
r: radius / 2 + diff
}
}, {
// 动画重复
repeat: true,
// 每一帧的操作,入参 ratio这一帧的比例值Number。返回值这一帧需要变化的参数集Object
onFrame(ratio) {
// 先变大、再变小
const diff = ratio <=0.5 ? ratio * 10 : (1 - ratio) * 10;
let radius = cfg.size;
if (isNaN(radius)) radius = radius[0];
// 返回这一帧需要变化的参数集,这里只包含了半径
return {
r: radius / 2 + diff
}
}
}, 3000, 'easeCubic'); // 一次动画持续的时长为 3000动画效果为 'easeCubic'
duration: 3000,
easing: 'easeCubic'
}); // 一次动画持续的时长为 3000动画效果为 'easeCubic'
}
}, 'circle'); // 该自定义节点继承了内置节点 'circle',除了被复写的 afterDraw 方法外,其他按照 'circle' 里的函数执行。
```
@ -87,7 +88,7 @@ G6.registerNode('circle-animate', {
#### 增加带有动画的背景图形
`afterDraw` 方法中为已有节点添加额外的 shape ,并为这些新增的图形设置动画。<br />
本例在 `afterDraw` 方法中,绘制了三个背景 circle ,分别使用不同的颜色填充,再调用 `animate` 方法实现这三个 circle 逐渐变大、变淡的动画。本例中没有使用 `onFrame` 函数,直接在 `animate` 函数的入参中设置每次动画结束时的最终目标样式,即半径增大 10透明度降为 0.1。<br />
本例在 `afterDraw` 方法中,绘制了三个背景 circle ,分别使用不同的颜色填充,再调用 `animate` 方法实现这三个 circle 逐渐变大、变淡的动画。本例中没有使用函数参数的形式,直接在 `animate` 函数的第一个参数中设置每次动画结束时的最终目标样式,即半径增大 10透明度降为 0.1。第二个参数设置动画的配置<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*FxDJQ5eY-5oAAAAAAAAAAABkARQnAQ' alt='download' width='150'/>
@ -136,23 +137,35 @@ G6.registerNode('background-animate', {
// 第一个背景圆逐渐放大,并消失
back1.animate({
r: r + 10,
opacity: 0.1,
opacity: 0.1
}, {
repeat: true // 循环
}, 3000, 'easeCubic', null, 0) // 无延迟
duration: 3000,
easing: 'easeCubic',
delay: 0 // 无延迟
})
// 第二个背景圆逐渐放大,并消失
back2.animate({
r: r + 10,
opacity: 0.1,
opacity: 0.1
}, {
repeat: true // 循环
}, 3000, 'easeCubic', null, 1000) // 1 秒延迟
duration: 3000,
easing: 'easeCubic',
delay: 1000 // 1 秒延迟
}) // 1 秒延迟
// 第三个背景圆逐渐放大,并消失
back3.animate({
r: r + 10,
opacity: 0.1,
opacity: 0.1
}, {
repeat: true // 循环
}, 3000, 'easeCubic', null, 2000) // 2 秒延迟
duration: 3000,
easing: 'easeCubic',
delay: 2000 // 2 秒延迟
})
}
}, 'circle');
```
@ -179,24 +192,23 @@ G6.registerNode('inner-animate', {
}
});
// 该图片 shape 的动画
image.animate({
// 动画重复
repeat: true,
// 每一帧的操作,入参 ratio这一帧的比例值Number。返回值这一帧需要变化的参数集Object
onFrame(ratio) {
// 旋转通过矩阵来实现
// 当前矩阵
const matrix = Util.mat3.create();
// 目标矩阵
const toMatrix = Util.transform(matrix, [
['r', ratio * Math.PI * 2]
]) ;
// 返回这一帧需要的参数集,本例中只有目标矩阵
return {
matrix: toMatrix
};
}
}, 3000, 'easeCubic');
image.animate((ratio) => { // 每一帧的操作,入参 ratio这一帧的比例值Number。返回值这一帧需要变化的参数集Object
// 旋转通过矩阵来实现
// 当前矩阵
const matrix = Util.mat3.create();
// 目标矩阵
const toMatrix = Util.transform(matrix, [
['r', ratio * Math.PI * 2]
]) ;
// 返回这一帧需要的参数集,本例中只有目标矩阵
return {
matrix: toMatrix
};
}, {
repeat: true, // 动画重复
duration: 3000,
easing: 'easeCubic'
});
}
}, 'rect');
```
@ -210,13 +222,13 @@ G6.registerNode('inner-animate', {
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*OAGPRZbYpw4AAAAAAAAAAABkARQnAQ' alt='download' width='150'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*VUgETK6aMzcAAAAAAAAAAABkARQnAQ' alt='download' width='110'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*VUgETK6aMzcAAAAAAAAAAABkARQnAQ' alt='download' width='150'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-l9lQ7Ck1QcAAAAAAAAAAABkARQnAQ' alt='download' width='150'/>
以上三个边动画的 demo 代码见:[边动画](https://codepen.io/Yanyan-Wang/pen/yLLJJoJ)
以上三个边动画的 demo 代码见:<a href='/zh/examples/scatter/edge' target='_blank'>边动画</a>
#### 圆点运动
本例通过在 afterDraw 方法中为边增加了一个 circle 图形,该图形沿着线运动。沿着线运动的原理:设定每一帧中,该 circle 在线上的相对位置。<br />
本例通过在 `afterDraw` 方法中为边增加了一个 circle 图形,该图形沿着线运动。沿着线运动的原理:设定每一帧中,该 circle 在线上的相对位置。<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*OAGPRZbYpw4AAAAAAAAAAABkARQnAQ' alt='download' width='150'/>
@ -239,20 +251,18 @@ G6.registerEdge('circle-running', {
});
// 对红色圆点添加动画
circle.animate({
// 动画重复
repeat: true,
// 每一帧的操作,入参 ratio这一帧的比例值Number。返回值这一帧需要变化的参数集Object
onFrame(ratio) {
// 根据比例值,获得在边 path 上对应比例的位置。
const tmpPoint = shape.getPoint(ratio);
// 返回需要变化的参数集,这里返回了位置 x 和 y
return {
x: tmpPoint.x,
y: tmpPoint.y
};
}
}, 3000); // 一次动画的时间长度
circle.animate((ratio) => { // 每一帧的操作,入参 ratio这一帧的比例值Number。返回值这一帧需要变化的参数集Object
// 根据比例值,获得在边 path 上对应比例的位置。
const tmpPoint = shape.getPoint(ratio);
// 返回需要变化的参数集,这里返回了位置 x 和 y
return {
x: tmpPoint.x,
y: tmpPoint.y
};
}, {
repeat: true, // 动画重复
duration: 3000
}); // 一次动画的时间长度
}
}, 'cubic'); // 该自定义边继承内置三阶贝塞尔曲线 cubic
```
@ -293,20 +303,18 @@ G6.registerEdge('line-dash', {
let index = 0;
// 边 path 图形的动画
shape.animate({
// 动画重复
repeat: true,
// 每一帧的操作,入参 ratio这一帧的比例值Number。返回值这一帧需要变化的参数集Object
onFrame(ratio) {
const cfg = {
lineDash: dashArray[index].concat(totalArray)
};
// 每次移动 1
index = (index + 1) % interval;
// 返回需要修改的参数集,这里只修改了 lineDash
return cfg;
}
}, 3000); // 一次动画的时长为 3000
shape.animate((ratio) => { // 每一帧的操作,入参 ratio这一帧的比例值Number。返回值这一帧需要变化的参数集Object
const cfg = {
lineDash: dashArray[index].concat(totalArray)
};
// 每次移动 1
index = (index + 1) % interval;
// 返回需要修改的参数集,这里只修改了 lineDash
return cfg;
}, {
repeat: true, // 动画重复
duration: 3000
}); // 一次动画的时长为 3000
}
}, 'cubic'); // 该自定义边继承了内置三阶贝塞尔曲线边 cubic
```
@ -321,32 +329,30 @@ G6.registerEdge('line-growth', {
afterDraw(cfg, group) {
const shape = group.get('children')[0];
const length = group.getTotalLength();
shape.animate({
// 动画重复
repeat: true,
// 每一帧的操作,入参 ratio这一帧的比例值Number。返回值这一帧需要变化的参数集Object
onFrame(ratio) {
const startLen = ratio * length;
// 计算线的lineDash
const cfg = {
lineDash: [startLen, length - startLen]
};
return cfg;
}
}, 2000); // 一次动画的时长为 2000
shape.animate((ratio) => { // 每一帧的操作,入参 ratio这一帧的比例值Number。返回值这一帧需要变化的参数集Object
const startLen = ratio * length;
// 计算线的lineDash
const cfg = {
lineDash: [startLen, length - startLen]
};
return cfg;
}, {
repeat: true, // 动画重复
duration: 2000 // 一次动画的时长为 2000
});
}
}, 'cubic'); // 该自定义边继承了内置三阶贝塞尔曲线边 cubic
```
### 交互动画
在交互的过程中也可以添加动画。如下图所示,当鼠标移到节点上时,所有与该节点相关联的边都展示虚线运动的动画。<br />![交互动画.gif](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-90pSrm4hkUAAAAAAAAAAABkARQnAQ)<br />上图完整 demo 即代码参见:[状态切换动画](/zh/examples/scatter/stateChange)
在交互的过程中也可以添加动画。如下图所示,当鼠标移到节点上时,所有与该节点相关联的边都展示虚线运动的动画。<br />![交互动画.gif](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-90pSrm4hkUAAAAAAAAAAABkARQnAQ)<br />上图完整 demo 即代码参见:<a href='/zh/examples/scatter/stateChange' target='_blank'>状态切换动画</a>
这种动画涉及到了边的 [状态](/zh/docs/manual/middle/states/state)。在自定义边时复写 `setState` 方法,可对边的各种状态进行监听。鼠标移动到节点上,相关边的某个状态被开启,`setState` 方法中监听到后开启动画效果。步骤如下:
- 自定义边中复写 `setState` 方法监听该边的状态,以及某状态下的动画效果;
- 监听中间的节点的 `mouseenter``mouseleave` 事件,触发相关边的状态变化。
下面代码节选自 demo [状态切换动画](/zh/examples/scatter/stateChange),请注意省略了部分代码,只展示了交互相关以及边动画相关的代码。
下面代码节选自 demo <a href='/zh/examples/scatter/stateChange' target='_blank'>状态切换动画</a>,请注意省略了部分代码,只展示了交互相关以及边动画相关的代码。
```javascript
// const data = ...
// const graph = new G6.Graph({...});
@ -382,18 +388,16 @@ G6.registerEdge('can-running', {
totalArray = totalArray.concat(lineDash);
}
let index = 0;
shape.animate({
// 动画重复
repeat: true,
// 每一帧的操作,入参 ratio这一帧的比例值Number。返回值这一帧需要变化的参数集Object
onFrame(ratio) {
const cfg = {
lineDash: dashArray[index].concat(totalArray)
};
index = (index + 1) % interval;
return cfg;
}
}, 3000); // 一次动画的时长为 3000
shape.animate((ratio) => { // 每一帧的操作,入参 ratio这一帧的比例值Number。返回值这一帧需要变化的参数集Object
const cfg = {
lineDash: dashArray[index].concat(totalArray)
};
index = (index + 1) % interval;
return cfg;
}, {
repeat: true, // 动画重复
duration: 3000 // 一次动画的时长为 3000
});
} else { // running 状态为 false 时
// 结束动画
shape.stopAnimate();
@ -428,6 +432,6 @@ graph.on('node:mouseleave', ev => {
// graph.render();
```
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;注意:</span>
running 为 false 时,要停止动画,同时把 lineDash 清空。
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;<strong>⚠️注意:</strong></span>
`running``false` 时,要停止动画,同时把 `lineDash` 清空。

View File

@ -1,19 +1,17 @@
---
title: 手动创建节点分组 Group
title: Create Node Group
order: 8
---
CustomGroup 为节点分组,支持 Circle 和 Rect 两种类型。用户可通过 CustomGroup 创建节点分组、设置分组的样式、计算分组的坐标及宽高、收起和展开分组。
By default, the Node Groups are rendered according to the data, which means G6 will find the array `groups` in the data for rendering. if the `groups` does not exist, the `groupId` in each element of `nodes` will take effect. No group will be rendered when both the `groups` and `groupId`s do not exist.
分组默认是根据数据自动渲染的,当数据中存在 `groups` 时根据 `groups` 字段渲染分组,当不存在 `groups` 时,则根据 `nodes` 数据中是否存在 `groupId` 来渲染分组。
CustomGroup is the customized Node Group, which supports Circle and Rect type Group. You can create a Node Group by CustomGroup, and set the group style, calculate the groups, and collapse / extend groups.
当需要通过手动创建分组时候,可以参考下面的文档。
## Instantialize the CustomGroup
The instances of CustomGroup will be created while instantiating the Graph. No manual instantiation is required.
## CustomGroup 实例化
CustomGroup 实例会在实例化 Graph 的过程中自动创建,不需要用户手动实例化。
## 配置项
在实例化 Graph 的时候,通过配置 `groupType``groupStyle` 来指定分组的类型及样式。
## Configuration
Configure the `groupType` and `groupStyle` to assign the group type and styles respectively when instantiating the Graph.
```javascript
const graph = new G6.Graph({
container: 'mountNode',
@ -29,46 +27,54 @@ const graph = new G6.Graph({
```
### groupType
groupType 属性用于指定分组的类型,默认为 `circle`,支持 `circle` 和 `rect`两种。
groupType is a string indicating the type of the Node Group. Options `'circle'` and `'rect'`. `'circle'` by default.
**groupType 指定为 `circle` 时**的效果如下。<br />
The reuslt of **groupType: `'circle'`**<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*0L2cTJVfPSwAAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
<br />**groupType 指定为 `rect` 时**的效果如下图。<br />
<br />The reuslt of **groupType: `'rect'`**<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*g_ntQK8Oz3cAAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
### groupStyle
`groupStyle` 用于指定分组在默认default、交互过程中hover及收起collapse状态下的样式。
`groupStyle` indicates the styles of the Node Groups in different states, e.g. default state, hover state, and collapse state.
#### 通用属性
default、hover 和 collapse 支持的所有通用的属性参考[属性配置项](/zh/docs/api/properties/NodeProperties)。除过这些通用的属性default 和 collapse 分别还支持以下特有属性。
#### Common Property
The common propertoes of the groups in the default, hover and collapse states are similar to nodes, which are introduced in [Shape Properties](/en/docs/api/shapeProperties). Besides, the group style in default and collapse states have some special properties below:
#### default
| 属性名称 | 含义 | 类型 | 备注 |
| Name | Description | Type | Remark |
| --- | --- | --- | --- |
| minDis | 距离右上角最小距离 | number | 不存在嵌套分组时使用该值 |
| maxDis | 距离右上角最大距离 | number | 存在嵌套分组时使用该值 |
| minDis | The padding of the Groups without nested structure | Number | No nested Group is the Group containing no other Groups |
| maxDis | Tha padding of the Groups with nested structure | Number | Nested Group is the Group containing other Groups |
The sketch about the `minDis` and `maxDis` when `groupType` is `'circle'`, where the group1 is the Group without nested structure, and the group2 is a nested Group.
<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*_hgTTaIPc8IAAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
The sketch about the `minDis` and `maxDis` when `groupType` is `'rect'`, where the group1 is the Group without nested structure, and the group2 is a nested Group.
<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*_IrBQqB0K2oAAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
#### collapse
| 属性名称 | 含义 | 类型 | 备注 |
| Name | Description | Type | Remark |
| --- | --- | --- | --- |
| r | 分组的半径 | number | 当 groupType 为 circle 时有效 |
| width | 分组宽度 | number | 当 groupType 为 rect 时有效 |
| height | 分组高度 | number | 当 groupType 为 rect 时有效 |
| r | The radius of the circle Group | Number | Takes effect when `groupType` is `'circle'` |
| width | The width of the rect Group | Number | Takes effect when `groupType` is `'rect'` |
| height | The height of the rect Group | Number | Takes effect when `groupType` is `'rect'` |
## add / addItem
用于生成分组。
Create Group.
| 参数 | 含义 | 类型 | 备注 |
| Name | Description | Type | Remark |
| --- | --- | --- | --- |
| groupId | 分组ID | string | |
| nodes | 分组中包含的节点或节点ID | array | 节点实例或节点 ID |
| type | 分组类型 | string | 默认 circle ,支持 circle 和 rect |
| zIndex | 分组层级 | number | 默认 0 |
| title | 分组标题配置 | object | string | 为 string 类型时,不能配置其他属性,为 object 时的配置参考[这里](https://www.yuque.com/antv/g6/inxeg8#07gsB) |
| groupId | The id of the Group | String | |
| nodes | The nodes or the id of the ndoes in the Group | Array | The array of node objects or ids |
| type | The type of the Group | String | Options: `'circle'`, `'rect'`. `'circle'` by default |
| zIndex | The zIndex of the Group | Number | `0` by default |
| title | The title text or the configurations | Object / String | When it is a string, the styles of it is uneditable. When it is an object, the configurations can be found in [Node Group](/en/docs/manual/middle/nodeGroup/#data-structure) |
```javascript
const nodes = ['node1', 'node2']
@ -77,9 +83,9 @@ graph.addItem('group', {
nodes,
type: 'rect',
zIndex: 2,
title: '分组标题',
title: 'The title text',
title: {
text: '分组标题',
text: 'The title text',
stroke: '',
fill: '',
offsetX: 10,
@ -88,11 +94,11 @@ graph.addItem('group', {
})
```
## collapseGroup
收起分组,收起分组后,隐藏分组中的所有节点和边,分组外部与分组内节点有连线的则临时连接到分组上面。
Hide the nodes and the edges when the Group is collapsed. The edges linked to the inner nodes will link to the group;
| 参数 | 含义 | 类型 | 备注 |
| Name | Description | Type | Remark |
| --- | --- | --- | --- |
| groupId | 分组ID | string | |
| groupId | The id of the Group | String | |
```javascript
@ -100,11 +106,11 @@ graph.collapseGroup('groupId')
```
## expandGroup
展开分组,显示分组中的所有节点和边,恢复收起前的连接情况。
The nodes and the edges will be restored when the Group is expand.
| 参数 | 含义 | 类型 | 备注 |
| Name | Description | Type | Remark |
| --- | --- | --- | --- |
| groupId | 分组ID | string | |
| groupId | The id of the Group | String | |
```javascript

View File

@ -3,9 +3,9 @@ title: 手动创建节点分组 Group
order: 8
---
CustomGroup 为节点分组,支持 Circle 和 Rect 两种类型。用户可通过 CustomGroup 创建节点分组、设置分组的样式、计算分组的坐标及宽高、收起和展开分组。
节点分组在默认情况下是根据数据自动渲染的,当数据中存在 `groups` 时根据 `groups` 字段渲染分组,当不存在 `groups` 时,则根据 `nodes` 数据中是否存在 `groupId` 来渲染分组。当数据中即不存在 `groups`,节点数据中也不存在 `groupId` 时,将不会渲染节点分组。
分组默认是根据数据自动渲染的,当数据中存在 `groups` 时根据 `groups` 字段渲染分组,当不存在 `groups` 时,则根据 `nodes` 数据中是否存在 `groupId` 来渲染分组。
CustomGroup 为节点分组,支持 Circle 和 Rect 两种类型。用户可通过 CustomGroup 创建节点分组、设置分组的样式、计算分组的坐标及宽高、收起和展开分组。
当需要通过手动创建分组时候,可以参考下面的文档。
@ -29,34 +29,42 @@ const graph = new G6.Graph({
```
### groupType
groupType 属性用于指定分组的类型,默认为 `circle`,支持 `circle` 和 `rect`两种。
`groupType` 属性用于指定分组的类型,默认为 `'circle'`,支持 `'circle'` 和 `'rect'`两种。
**groupType 指定为 `circle` 时**的效果如下。<br />
**groupType 指定为 `'circle'` 时**的效果如下。<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*0L2cTJVfPSwAAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
<br />**groupType 指定为 `rect` 时**的效果如下图。<br />
<br />**groupType 指定为 `'rect'` 时**的效果如下图。<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*g_ntQK8Oz3cAAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
### groupStyle
`groupStyle` 用于指定分组在默认default、交互过程中hover及收起collapse状态下的样式。
#### 通用属性
default、hover 和 collapse 支持的所有通用的属性参考[属性配置项](/zh/docs/api/properties/NodeProperties)。除过这些通用的属性default 和 collapse 分别还支持以下特有属性。
default、hover 和 collapse 支持的所有通用的属性参考[图形属性](/zh/docs/api/shapeProperties)。除过这些通用的属性default 和 collapse 分别还支持以下特有属性。
#### default
| 属性名称 | 含义 | 类型 | 备注 |
| --- | --- | --- | --- |
| minDis | 距离右上角最小距离 | number | 不存在嵌套分组时使用该值 |
| maxDis | 距离右上角最大距离 | number | 存在嵌套分组时使用该值 |
| minDis | 最内层(无嵌套)的 Group 的 padding | Number | 无嵌套,即该 Group 内不含有其他 Group |
| maxDis | 内嵌有其他节点分组的 Group 的 padding | Number | 嵌套 Group即该 Group 内有其他 Group 时使用该值 |
`groupType` 指定为 `'circle'` 时的 `minDis``maxDis` 示意图。其中 group1 为无嵌套的 Group即最内层的 Groupgroup2 为嵌套 Group。
<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*_hgTTaIPc8IAAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
`groupType` 指定为 `'rect'` 时的 `minDis``maxDis` 示意图。其中 group1 为无嵌套的 Group即最内层的 Groupgroup2 为嵌套 Group。
<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*_IrBQqB0K2oAAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
#### collapse
| 属性名称 | 含义 | 类型 | 备注 |
| --- | --- | --- | --- |
| r | 分组的半径 | number | 当 groupType 为 circle 时有效 |
| width | 分组宽度 | number | 当 groupType 为 rect 时有效 |
| height | 分组高度 | number | 当 groupType 为 rect 时有效 |
| r | 分组的半径 | Number | 当 `groupType``'circle'` 时有效 |
| width | 分组宽度 | Number | 当 `groupType``'rect'` 时有效 |
| height | 分组高度 | Number | 当 `groupType` 为 `'rect'` 时有效 |
## add / addItem
@ -64,11 +72,11 @@ default、hover 和 collapse 支持的所有通用的属性参考[属性配置
| 参数 | 含义 | 类型 | 备注 |
| --- | --- | --- | --- |
| groupId | 分组ID | string | |
| nodes | 分组中包含的节点或节点ID | array | 节点实例或节点 ID |
| type | 分组类型 | string | 默认 circle ,支持 circle 和 rect |
| zIndex | 分组层级 | number | 默认 0 |
| title | 分组标题配置 | object | string | 为 string 类型时,不能配置其他属性,为 object 时的配置参考[这里](https://www.yuque.com/antv/g6/inxeg8#07gsB) |
| groupId | 分组 ID | String | |
| nodes | 分组中包含的节点或节点 ID | Array | 节点实例或节点 ID |
| type | 分组类型 | String | 默认 `'circle'` ,支持 `'circle'``'rect'` |
| zIndex | 分组层级 | Number | 默认 `0` |
| title | 分组标题配置 | Object / String | 为 String 类型时,不能配置其他属性,为 Object 时的配置参考[这里](/zh/docs/manual/middle/nodeGroup/#数据结构) |
```javascript
const nodes = ['node1', 'node2']
@ -92,7 +100,7 @@ graph.addItem('group', {
| 参数 | 含义 | 类型 | 备注 |
| --- | --- | --- | --- |
| groupId | 分组ID | string | |
| groupId | 分组 ID | String | |
```javascript
@ -104,7 +112,7 @@ graph.collapseGroup('groupId')
| 参数 | 含义 | 类型 | 备注 |
| --- | --- | --- | --- |
| groupId | 分组ID | string | |
| groupId | 分组 ID | String | |
```javascript

View File

@ -1,50 +1,51 @@
---
title: 自定义交互 Behavior
title: Custom Behavior
order: 5
---
G6 除了提供丰富的 [内置交互行为 Behavior](/zh/docs/manual/middle/states/defaultBehavior) 外,还提供了自定义交互行为的机制,方便用户开发更加定制化的交互行为。
G6 provides abundant [Built-in Behavior](/en/docs/manual/middle/states/defaultBehavior). Besides, you can custom your type of behaviors to satisfy the special requirements.
在交互行为上, G6 主要考虑了三个场景:
In G6, we mainly take three scenarios into consideration:
- 展示关系数据;
- 可视化建模;
- 图分析。
- Demonstrating the relational data;
- Modeling the visualization;
- Analyzing the graph.
在这些场景中只要用户可能无法一眼看清楚所有需要的信息,都需要进行交互,例如:
It is necessary to incorporate the interactions when the information is too complex to be understand in one glance:
- 图太大,需要缩放;
- 单个节点上展示的信息太少,需要通过 tooltip 显示详情;
- 对节点进行增删改查。
- Zooming a large graph;
- Utilizing the ttoltip to show the detail information of a node;
- Adding/removing/modifying/querying a graph item.
我们无法将所有常用的交互全部内置到 G6 中。由于场景不一样,业务不一样,同样的目的需要的交互都不一样:
Due to the complex and the diversity of the interactions in different scenarios and bussiness, we did not build all the interactions into G6:
- 有些系统需要从工具栏上点击后添加节点,有些系统需要从面板栏上拖出出新的节点;
- 有的业务添加边需要从锚点上拖拽出来,而有些直接点击节点后就可以拖拽出边;
- 有些边可以连接到所有节点上,而有些边不能连接到具体某个节点的某个锚点上;
- 所有的交互的触发、持续、结束都要允许能够进行个性化的判定。
- Some systems require to add nodes by clicking a tool bar, some require toe add by dragging from a panel;
- Some scenarios add edges by dragging from an anchor point, some add by clicking the end nodes;
- Some edges are allowed to link to any node, some only can be linked to specific anchor points;
- Some users require to custom the process of activating and endding.
- ...
我们可以看到在图上的交互是繁杂多变的。各种冲突、各种配置项会让用户和开发者疲于应对。出于这些考虑, G6 提供了一套非常简单而灵活的机制来实现交互。
We found the interactions are sundry and versatile. And the conflicts and configurations will make the users and developers collapse. Thus, G6 designs a set of simple and flexible implemention of interaction behavior.
## Behavior 的生命周期
为实现交互,首先需要了解交互的生命周期。交互起源于用户在系统上的所有事件,是否允许交互发生同事件密切相关。所以我们看到交互的生命周期,即操作事件的过程如下:
## The Life Cycle of Behavior
To customize a Behavior, it is important to comprehend the life cycle of Behavior. Interaction Behaviors are related to the events from users, including the processes:
- 绑定事件;
- 触发事件;
- 持续事件;
- 结束事件;
- 移除事件。
- Bind the event;
- Activate the event;
- Keep the event;
- End the event;
- Remove the event.
## 自定义交互 registerBehavior
通过 `G6.registerBehavior` 自定义 Behavior。下面代码实现了名为 `'activate-node' `的交互行为,在终端用户点击节点时,置该节点的 `active` 状态为 `true`;再次点击或点击画布时,置该节点的 `active` 状态为 `false`
## registerBehavior
You can customize a Behavior by `G6.registerBehavior`. The following code implements a custom Behavior named `'activate-node'`, which changes the state `active` of the clicked node to be `true`, and restores the state `active` to be `false` when the user clicking the node again or clicking the canvas.
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;注意:</span>
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;⚠️**Attension:** </span>
- 下面代码仅设置了不同交互后节点的状态,没有指定这些状态下节点的样式。若需要根据节点状态变化它的样式,参见 [配置不同 State 样式](/zh/docs/manual/middle/states/state)。
- 自定义 Behavior 时,可选的方法请参数 [Behavior API](/zh/docs/api/Behavior)
- `getEvent` 返回该 Behavior 所需监听事件的对象G6 中支持的所有事件,请参考 [Event API](/zh/docs/api/Event)。
- The following code set the states for different behaviors, but does not assign the state styles for manipulated nodes. To change the styles when the states changed, refer to [State Styles](/en/docs/manual/middle/states/state).
- The configurations of customizing Behavior are introduced in [Behavior API](/en/docs/api/Behavior)
- `getEvent` returns the events which are listened by the Behavior. The events in G6 are introduced in [Event API](/en/docs/api/Event).
```javascript
G6.registerBehavior('activate-node', {
@ -66,21 +67,21 @@ G6.registerBehavior('activate-node', {
graph.setItemState(item, 'active', false);
return;
}
// this 上即可取到配置如果不允许多个active先取消其他节点的active状态
// Get the configurations by this. If you do not allow multiple nodes to be 'active', cancel the 'active' state for other nodes
if (!this.multiple) {
this.removeNodesState();
}
// 置点击的节点状态为active
// Set the 'active' state of the clicked node to be true
graph.setItemState(item, 'active', true);
},
onCanvasClick(e) {
// shouldUpdate可以由用户复写,返回 true 时取消所有节点的active状态
// shouldUpdate can be rewrited by users. Returning true means turning the 'active' to be false for all the nodes
if (this.shouldUpdate(e)) {
removeNodesState();
}
},
removeNodesState() {
graph.findAllByState('active').forEach(node => {
graph.findAllByState('node', 'active').forEach(node => {
graph.setItemState(node, 'active', false);
});
}
@ -88,15 +89,15 @@ G6.registerBehavior('activate-node', {
```
## 使用自定义的 Behavior
有了上面代码定义的名为 `'activate-node'` 的 Behavior 以后,在实例化 Graph 时,在 `modes` 中将其配置到默认或其他[行为模式](/zh/docs/manual/middle/states/mode)中。下面代码将其配置到了默认行为模式中,在默认模式下,该行为将会生效。
## Using Behavior
Now, you have a type of Behavior named `'activate-node'`. To use it, configure it into a mode of `modes` when instantiating a Graph. [Mode](/en/docs/manual/middle/states/mode). The following code configure the `'activate-node'` into the default mode, which means the `'activate-node'` Behavior will take effect in the default mode.
```javascript
const graph = new G6.Graph({
container: 'mountNode',
width: 500,
height: 500,
modes: {
// 定义的 behavior 指定到这里就可以支持Behavior中定义的交互
// Configure the custom Behavior here to use it
default: ['activate-node']
}
});

View File

@ -22,9 +22,10 @@ G6 除了提供丰富的 [内置交互行为 Behavior](/zh/docs/manual/middle/st
- 有些系统需要从工具栏上点击后添加节点,有些系统需要从面板栏上拖出出新的节点;
- 有的业务添加边需要从锚点上拖拽出来,而有些直接点击节点后就可以拖拽出边;
- 有些边可以连接到所有节点上,而有些边不能连接到具体某个节点的某个锚点上;
- 所有的交互的触发、持续、结束都要允许能够进行个性化的判定。
- 所有的交互的触发、持续、结束都要允许能够进行个性化的判定;
- ……
我们可以看到在图上的交互是繁杂多变的。各种冲突、各种配置项会让用户和开发者疲于应对。出于这些考虑, G6 提供了一套非常简单而灵活的机制来实现交互。
我们可以看到在图上的交互是繁杂多变的。各种冲突、各种配置项会让用户和开发者疲于应对。出于这些考虑G6 提供了一套非常简单而灵活的机制来实现交互。
## Behavior 的生命周期
@ -38,11 +39,11 @@ G6 除了提供丰富的 [内置交互行为 Behavior](/zh/docs/manual/middle/st
## 自定义交互 registerBehavior
通过 `G6.registerBehavior` 自定义 Behavior。下面代码实现了名为 `'activate-node' `的交互行为,在终端用户点击节点时,置该节点的 `active` 状态为 `true`;再次点击或点击画布时,置该节点的 `active` 状态为 `false`
通过 `G6.registerBehavior` 自定义 Behavior。下面代码实现了名为 `'activate-node'` 的交互行为,在终端用户点击节点时,置该节点的 `active` 状态为 `true`;再次点击或点击画布时,置该节点的 `active` 状态为 `false`
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;注意:</span>
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;<strong>⚠️注意:</strong></span>
- 下面代码仅设置了不同交互后节点的状态,没有指定这些状态下节点的样式。若需要根据节点状态变化它的样式,参见 [配置不同 State 样式](/zh/docs/manual/middle/states/state)。
- 下面代码仅设置了不同交互后节点的状态,没有指定这些状态下节点的样式。若需要根据节点状态变化它的样式,参见 [配置不同 State 下的节点样式](/zh/docs/manual/middle/states/state)。
- 自定义 Behavior 时,可选的方法请参数 [Behavior API](/zh/docs/api/Behavior)
- `getEvent` 返回该 Behavior 所需监听事件的对象G6 中支持的所有事件,请参考 [Event API](/zh/docs/api/Event)。
@ -66,21 +67,21 @@ G6.registerBehavior('activate-node', {
graph.setItemState(item, 'active', false);
return;
}
// this 上即可取到配置如果不允许多个active先取消其他节点的active状态
// this 上即可取到配置,如果不允许多个 'active',先取消其他节点的 'active' 状态
if (!this.multiple) {
this.removeNodesState();
}
// 置点击的节点状态为active
// 置点击的节点状态 'active' 为 true
graph.setItemState(item, 'active', true);
},
onCanvasClick(e) {
// shouldUpdate可以由用户复写返回 true 时取消所有节点的active状态
// shouldUpdate 可以由用户复写,返回 true 时取消所有节点的 'active' 状态,即将 'active' 状态置为 false
if (this.shouldUpdate(e)) {
removeNodesState();
}
},
removeNodesState() {
graph.findAllByState('active').forEach(node => {
graph.findAllByState('node', 'active').forEach(node => {
graph.setItemState(node, 'active', false);
});
}
@ -96,7 +97,7 @@ const graph = new G6.Graph({
width: 500,
height: 500,
modes: {
// 定义的 behavior 指定到这里就可以支持Behavior中定义的交互
// 定义的 Behavior 指定到这里,就可以支持 Behavior 中定义的交互
default: ['activate-node']
}
});

View File

@ -1,23 +1,27 @@
---
title: 自定义边
title: Custom Edge
order: 3
---
G6 除了提供丰富的 [内置边](/zh/docs/manual/middle/elements/defaultEdge) 外,还提供了自定义边的机制,方便用户开发更加定制化的边,包括含有复杂图形的边、复杂交互的边、带有动画的边等。
G6 provides abundant [Built-in Edges](/en/docs/manual/middle/elements/edges/defaultEdge). Besides, the custom machanism allows the users to design their own type of edges. An edge with complex graphics shapes, complex interactions, fantastic animations can be implemented easily.
在本章中我们会通过四个案例,从简单到复杂讲解边的自定义:<br />1. 从无到有的定义边;<br />2. 扩展现有边:<br />3. 边的交互样式;<br />4. 自定义带箭头的边。
In this document, we will introduce the custom edge by four examples:
<br />1. Register a bran-new edge;
<br />2. Register an edge by extending a built-in edge;
<br />3. Register an edge with interactions and styles;
<br />4. Register an edge with custom arrow.
## 1. 从无到有定义边
我们来实现垂直的折线:<br />
## 1. Register a Bran-new Edge
Now, we are goint to register a perpendicular polyline:<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*HxY-TJ2vJFMAAAAAAAAAAABkARQnAQ' alt='img' width='150'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Ijy4QpaB-fgAAAAAAAAAAABkARQnAQ' alt='img' width='150'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*gz09R5fM-HMAAAAAAAAAAABkARQnAQ' alt='img' width='150'/>
> (左)直线边。(中)默认的折线边。(右)调整了节点的控制点后的折线边。
> (Left) Straight line edge. (Center) A custom polyline edge. (Right) The result after modifying the link points of the end nodes.
### 自定义边
### Register a Custom Edge
```javascript
G6.registerEdge('hvh', {
draw(cfg, group) {
@ -28,8 +32,8 @@ G6.registerEdge('hvh', {
stroke: '#333',
path: [
['M', startPoint.x, startPoint.y],
['L', endPoint.x / 3 + 2 / 3 * startPoint.x , startPoint.y], // 三分之一处
['L', endPoint.x / 3 + 2 / 3 * startPoint.x , endPoint.y], // 三分之二处
['L', endPoint.x / 3 + 2 / 3 * startPoint.x , startPoint.y], // 1/3
['L', endPoint.x / 3 + 2 / 3 * startPoint.x , endPoint.y], // 2/3
['L', endPoint.x, endPoint.y]
]
}
@ -39,11 +43,12 @@ G6.registerEdge('hvh', {
});
```
- 默认的 `startPoint` `endPoint` 是两个端点中点的连接线分别同圆的交点;
- 修改节点的锚点可以修改 `startPoint``endPoint` 的位置。
Now, we have registered a custom edge named `'hvh'` whose result is shown in the center of the figure above. The default `startPoint` and `endPoint` in the custom edge are the intersection of the edge and the end nodes.
### 示例数据
通过以下的数据,使用自定义的 hvh 边,就可以实现上图最右边的效果。
To achieve the result shown in the right of the figure, we modify the anchorPoints (link points) of the end nodes to change the positions of `startPoint` and `endPoint`.
### Modify the anchorPoints in Data
Now, we modify `anchorPoints` in the node data, and then assign `shape` to `'hvh'` in edge data as shown below.
```javascript
const data = {
nodes: [{
@ -82,50 +87,53 @@ const data = {
};
```
## 2. 扩展现有边
通过 `afterDraw` 接口给现有的曲线增加动画。
## 2. Extend the Built-in Edge
In this section, we add animation to a built-in edge by `afterDraw`.
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-l9lQ7Ck1QcAAAAAAAAAAABkARQnAQ' alt='img' width='150'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-l9lQ7Ck1QcAAAAAAAAAAABkARQnAQ' alt='img' width='250'/>
```javascript
G6.registerEdge('line-growth', {
afterDraw(cfg, group) {
const shape = group.get('children')[0];
const length = shape.getTotalLength();
shape.animate({
onFrame(ratio) {
const startLen = ratio * length;
const cfg = {
lineDash: [startLen, length - startLen]
};
return cfg;
},
repeat: true
}, 2000);
shape.animate((ratio) => {
const startLen = ratio * length;
const cfg = {
lineDash: [startLen, length - startLen]
};
return cfg;
}, {
repeat: true,
duration: 2000
});
}
}, 'cubic');
```
<br />
## 3. 边的交互样式
以点击选中、鼠标 hover 到边为示例,实现如下需求:
## 3. Custom Edge with Interaction Styles
In this section, we implement a type of edge with the interaction styles below:
- 点击边时边变粗,再点击变成细;
- 鼠标移动上去变成红色,离开变成 `'#333'`
- Widen the edge by clicking. Restore it by clicking again;
- Turn to red by mouse hovering. Restore it by mouse leaving.
效果如下图所示。<br />
The result:<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*IWLxRZomOfMAAAAAAAAAAABkARQnAQ' alt='img' width='350'/>
<br />提示:边如果过细点击时很难击中,可以设置 `**lineAppendWidth**` 来提升击中范围。
<br />
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)">
<strong>Attention:</strong>
</span> when the edge is too thin to be hitted by mouse, set `lineAppendWidth` to enlarge the hitting area.
```javascript
// 基于 line 扩展出新的图形
// Extend a new type of edge by extending line edge
G6.registerEdge('custom-edge', {
// 设置状态
// Response the states change
setState(name, value, item) {
const group = item.getContainer();
const shape = group.get('children')[0]; // 顺序根据 draw 时确定
const shape = group.get('children')[0]; // The order is determined by the ordering of been draw
if(name === 'active') {
if(value) {
shape.attr('stroke', 'red');
@ -143,10 +151,10 @@ G6.registerEdge('custom-edge', {
}
}, 'line');
// 点击时选中,再点击时取消
// Select by clicking, cancel by clicking again
graph.on('edge:click', ev=> {
const edge = ev.item;
graph.setItemState(edge, 'selected', !edge.hasState('selected')); // 切换选中
graph.setItemState(edge, 'selected', !edge.hasState('selected')); // Switch the 'selected' state
});
graph.on('edge:mouseenter' ,ev=> {
@ -163,12 +171,12 @@ graph.on('edge:mouseleave' , ev=> {
<br />
## 4. 自定义带箭头的边
很多时候G6 默认提供的箭头并不能满足业务上的需求这个时候就需要我们自定义箭头。当然了G6 也支持箭头样式的自定义。<br />
## 4. Register Edge with Custom Arrow
The default end arrows might not meet the requirements sometimes. You can register an edge with a custom arrow by the custom mechanism of G6.<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*f1G9RJ5dE2oAAAAAAAAAAABkARQnAQ' alt='img' width='250'/>
> G6 内置箭头。(右)自定义边带有自定义箭头。
> (Left) Built-in arrow of G6. (Right) A custom edge with custom arrow.
```javascript

View File

@ -3,7 +3,7 @@ title: 自定义边
order: 3
---
G6 除了提供丰富的 [内置边](/zh/docs/manual/middle/elements/defaultEdge) 外,还提供了自定义边的机制,方便用户开发更加定制化的边,包括含有复杂图形的边、复杂交互的边、带有动画的边等。
G6 除了提供丰富的 [内置边](/zh/docs/manual/middle/elements/edges/defaultEdge) 外,还提供了自定义边的机制,方便用户开发更加定制化的边,包括含有复杂图形的边、复杂交互的边、带有动画的边等。
在本章中我们会通过四个案例,从简单到复杂讲解边的自定义:<br />1. 从无到有的定义边;<br />2. 扩展现有边:<br />3. 边的交互样式;<br />4. 自定义带箭头的边。
@ -15,7 +15,7 @@ G6 除了提供丰富的 [内置边](/zh/docs/manual/middle/elements/defaultEdge
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Ijy4QpaB-fgAAAAAAAAAAABkARQnAQ' alt='img' width='150'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*gz09R5fM-HMAAAAAAAAAAABkARQnAQ' alt='img' width='150'/>
> (左)直线边。(中)默认的折线边。(右)调整了节点的控制点后的折线边。
> (左)直线边。(中)默认的折线边。(右)调整了节点的锚点(连入点)后的折线边。
### 自定义边
```javascript
@ -39,10 +39,10 @@ G6.registerEdge('hvh', {
});
```
- 默认的 `startPoint` `endPoint` 是两个端点中点的连接线分别同圆的交点;
- 修改节点的锚点可以修改 `startPoint``endPoint` 的位置。
- 上面自定义边中的 `startPoint``endPoint` 分别是是边两端与起始节点和结束节点的交点;
- 可以通过修改节点的锚点(边连入点)来改变 `startPoint``endPoint` 的位置。
### 示例数据
### 在数据中修改 anchorPoints
通过以下的数据,使用自定义的 hvh 边,就可以实现上图最右边的效果。
```javascript
const data = {
@ -85,23 +85,23 @@ const data = {
## 2. 扩展现有边
通过 `afterDraw` 接口给现有的曲线增加动画。
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-l9lQ7Ck1QcAAAAAAAAAAABkARQnAQ' alt='img' width='150'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-l9lQ7Ck1QcAAAAAAAAAAABkARQnAQ' alt='img' width='250'/>
```javascript
G6.registerEdge('line-growth', {
afterDraw(cfg, group) {
const shape = group.get('children')[0];
const length = shape.getTotalLength();
shape.animate({
onFrame(ratio) {
const startLen = ratio * length;
const cfg = {
lineDash: [startLen, length - startLen]
};
return cfg;
},
repeat: true
}, 2000);
shape.animate((ratio) => {
const startLen = ratio * length;
const cfg = {
lineDash: [startLen, length - startLen]
};
return cfg;
}, {
repeat: true,
duration: 2000
});
}
}, 'cubic');
```
@ -117,12 +117,15 @@ G6.registerEdge('line-growth', {
效果如下图所示。<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*IWLxRZomOfMAAAAAAAAAAABkARQnAQ' alt='img' width='350'/>
<br />提示:边如果过细点击时很难击中,可以设置 `**lineAppendWidth**` 来提升击中范围。
<br />
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"><strong>⚠️注意:</strong></span>
边如果过细点击时很难击中,可以设置 `lineAppendWidth` 来提升击中范围。
```javascript
// 基于 line 扩展出新的图形
// 基于 line 扩展出新的
G6.registerEdge('custom-edge', {
// 设置状态
// 响应状态变化
setState(name, value, item) {
const group = item.getContainer();
const shape = group.get('children')[0]; // 顺序根据 draw 时确定

View File

@ -1,64 +1,64 @@
---
title: 自定义布局 Layout
title: Custom Layout
order: 4
---
G6 提供了一般图和树图的一些常用布局,使用方式参见:中级教程 [使用布局 Layout](/zh/docs/manual/middle/layout)[Layout API](/zh/docs/api/Layout)。当这些内置布局无法满足需求时G6 还提供了一般图的自定义布局的机制,方便用户进行更定制化的扩展。
G6 provides abundant commonly used built-in layouts for Graph and TreeGraph respectively. The usage can be found in: [Utilizing Layout](/en/docs/manual/middle/layout), [Layout API](/en/docs/api/layout/Layout). Custom layout mechanism of G6 allows the users to design their own type of layout to meet their special requirements.
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;注意:</span>
树图暂时不支持自定义布局。
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;<strong>Attention:</strong> </span>
The TreeGraph does not support custom layout temporarily.
本文将会通过自定义 Bigraph 布局的例子讲解自定义布局。
In this document, we will introduce the custom layout by registering a layout for Bigraph.
## 自定义布局 API
G6 中自定义布局的 API 如下:
## The API of Cumstom Layout
```javascript
/**
* 注册布局的方法
* @param {string} type 布局类型,外部引用指定必须,不要与已有布局类型重名
* @param {object} layout 布局方法
* Register a Layout
* @param {string} type The layout type is must assigned to an unique string
* @param {object} layout The layout method
*/
Layout.registerLayout = function(type, {
/**
* 定义自定义行为的默认参数,会与用户传入的参数进行合并
* The default configurations of the custom layout. It will be mixed by the configurations from users
*/
getDefaultCfg() {
return {};
},
/**
* 初始化
* @param {object} data 数据
* Initialize
* @param {object} data data
*/
init(data) {},
/**
* 执行布局
* Execute the layout
*/
execute() {},
/**
* 根据传入的数据进行布局
* Layout with the data
* @param {object} data 数据
*/
layout(data) {},
/**
* 更新布局配置,但不执行布局
* @param {object} cfg 需要更新的配置项
* Update the layout configurations, but do not execute the layout
* @param {object} cfg The new configurations
*/
updateCfg(cfg) {},
/**
* 销毁
* Destroy
*/
destroy() {},
});
```
## 自定义布局
下面,我们将讲解如何自定义布局如下图的二分图 Bigraph。二分图只存在两部分节点之间的边同属于一个部分的节点之间没有边。我们希望布局能够对两部分节点分别进行排序减少边的交叉。<br />
## Custom Layout
Now, we are going to register a layout for Bigraph. Bigraph is the graph with nodes divided into two parts. There will be no edges between the nodes which are belong to the same part. In the custom layout, we sort the nodes according to their topology to reduce the edge crossings.<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*FksvTrdkqXgAAAAAAAAAAABkARQnAQ' alt='img' width='350'/>
该二分图数据如下,节点根据 `cluster` 字段分为 了 `'part1'``'part2'`,代表二分图的两部分。
The data of the Bigraph is shown below, where the nodes are divided into `'part1'` and `'part2'` by the property `cluster`.
```javascript
const data = {
nodes: [
@ -91,32 +91,32 @@ const data = {
};
```
### 需求分析
为了减少边的交叉,可以通过排序,将 `'part1'` 的节点 A 对齐到所有与 A 相连的 `'part2'` 中的节点的平均中心;同样将 `'part2'` 中的节点 a 对齐到所有与 a 相连的 `'part1'` 中的节点的平均中心。可以描述成如下过程:
### Requirements Analysis
To reduce the edge crossings, we sort the nodes in `part1` and `part2` respectively. The process is:
- Step 1:为 `'part1'` 和 `'part2'` 的节点初始化随机序号 index都分别从 0 开始;
- Step 2:遍历 `'part1'` 的节点,对每一个节点 A
- 找到与 A 相连的属于 `'part2'` 的节点的集合 ![]( https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-WOhQIGg9l8AAAAAAAAAAABkARQnAQ),加和 ![]( https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-WOhQIGg9l8AAAAAAAAAAABkARQnAQ) 中所有节点的 index并除以 ![]( https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-WOhQIGg9l8AAAAAAAAAAABkARQnAQ) 的元素个数,得数覆盖 A 的 index 值:![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*VfXiSK1f02cAAAAAAAAAAABkARQnAQ)
- Step 3:遍历 `'part1'` 的节点,对每一个节点 B Step 2 相似):
- 找到与 B 相连的属于 `'part2'` 的节点的集合 ![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GqZiSKI-nB8AAAAAAAAAAABkARQnAQ),加和 ![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GqZiSKI-nB8AAAAAAAAAAABkARQnAQ) 中所有节点的 index并除以 ![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GqZiSKI-nB8AAAAAAAAAAABkARQnAQ) 的元素个数,得数覆盖 B 的 index 值:![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-8b2Spfb4HIAAAAAAAAAAABkARQnAQ)
- Step 4:两部分节点分别按照节点的序号 index 进行排序,最终按照节点顺序安排节点位置。
- Step 1: Assign the index from 0 randomly for the nodes in `'part1'` and `'part2'` respectively;
- Step 2: Traverse the nodes in `'part1'`. For each node A:
- Find the set of related nodes of A (connect to A directly) in `'part2'` ![]( https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-WOhQIGg9l8AAAAAAAAAAABkARQnAQ). Sum up the indexes of the nodes in ![]( https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-WOhQIGg9l8AAAAAAAAAAABkARQnAQ), and divided it by the number of elements in ![]( https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-WOhQIGg9l8AAAAAAAAAAABkARQnAQ). Replace the index of A by the result: ![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*VfXiSK1f02cAAAAAAAAAAABkARQnAQ)
- Step 3: Tranverse the nodes in `'part2'`. For each node A(Similar to the Step 2):
- Find the set of related nodes of B (connect to B directly) in `'part1'` ![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GqZiSKI-nB8AAAAAAAAAAABkARQnAQ). Sum up the indexes of the nodes in ![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GqZiSKI-nB8AAAAAAAAAAABkARQnAQ), and divided it by the number of elements in ![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GqZiSKI-nB8AAAAAAAAAAABkARQnAQ). Replace the index of A by the result: ![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-8b2Spfb4HIAAAAAAAAAAABkARQnAQ)
- Step 4: Sort the nodes in `part1` and `part2` respectively according to their indexed. The result order determine the postions of the nodes in the final layout.
## 实现
下面代码展示了自定义名为 `'bigraph-layout'` 的二分图布局,完整代码参见:[自定义布局-二分图](/zh/examples/net/layoutMechanism#customBigraph)。使用该布局的方式与使用内置布局方式相同,都是在实例化图时将其配置到 `layout` 配置项中,详见:[使用布局 Layout](/zh/docs/manual/middle/layout)。
## Implementation
The following code below register a layout named `'bigraph-layout'` for Bigraph. The complete code can be found in: <a href='/en/examples/net/layoutMechanism#customBigraph' target='_blank'>Cusom Layout-Bigraph</a>. The usage of custom layout is the same as built-in layouts: configure the `layout` to the graph when instantiating. Refer to: [Utilizing Layout](/en/docs/manual/middle/layout).
```javascript
G6.registerLayout('bigraph-layout', {
// 默认参数
// Default configurations
getDefaultCfg: function getDefaultCfg() {
return {
center: [0, 0], // 布局的中心
biSep: 100, // 两部分的间距
nodeSep: 20, // 同一部分的节点艰巨
direction: 'horizontal', // 两部分的分布方向
nodeSize: 20 // 节点大小
center: [0, 0], // The center of the layout
biSep: 100, // The separation of these two parts
nodeSep: 20, // The separation between nodes in the same part
direction: 'horizontal', // The direction of the two parts
nodeSize: 20 // The node size
};
},
// 执行布局
// Execute the layout
execute: function execute() {
var self = this;
var center = self.center;
@ -125,7 +125,7 @@ G6.registerLayout('bigraph-layout', {
var nodeSize = self.nodeSize;
var part1Pos = 0,
part2Pos = 0;
// 若指定为横向分布
// Layout the graph in horizontally
if (self.direction === 'horizontal') {
part1Pos = center[0] - biSep / 2;
part2Pos = center[0] + biSep / 2;
@ -136,7 +136,7 @@ G6.registerLayout('bigraph-layout', {
var part2Nodes = [];
var part1NodeMap = new Map();
var part2NodeMap = new Map();
// separate the nodes and init the positions
// Separate the nodes and init the positions
nodes.forEach(function(node, i) {
if (node.cluster === 'part1') {
part1Nodes.push(node);
@ -147,7 +147,7 @@ G6.registerLayout('bigraph-layout', {
}
});
// 对 part1 的节点进行排序
// Sort the nodes in part1
part1Nodes.forEach(function(p1n) {
var index = 0;
var adjCount = 0;
@ -169,7 +169,7 @@ G6.registerLayout('bigraph-layout', {
return a.index - b.index;
});
// 对 part2 的节点进行排序
// Sort the nodes in part2
part2Nodes.forEach(function(p2n) {
var index = 0;
var adjCount = 0;
@ -191,7 +191,7 @@ G6.registerLayout('bigraph-layout', {
return a.index - b.index;
});
// 放置节点
// Place the ndoes
var hLength = part1Nodes.length > part2Nodes.length ? part1Nodes.length : part2Nodes.length;
var height = hLength * (nodeSep + nodeSize);
var begin = center[1] - height / 2;

View File

@ -3,9 +3,9 @@ title: 自定义布局 Layout
order: 4
---
G6 提供了一般图和树图的一些常用布局,使用方式参见:中级教程 [使用布局 Layout](/zh/docs/manual/middle/layout)[Layout API](/zh/docs/api/Layout)。当这些内置布局无法满足需求时G6 还提供了一般图的自定义布局的机制,方便用户进行更定制化的扩展。
G6 提供了一般图和树图的一些常用布局,使用方式参见:中级教程 [使用布局 Layout](/zh/docs/manual/middle/layout)[Layout API](/zh/docs/api/layout/Layout)。当这些内置布局无法满足需求时G6 还提供了一般图的自定义布局的机制,方便用户进行更定制化的扩展。
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;注意:</span>
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;<strong>⚠️注意:</strong></span>
树图暂时不支持自定义布局。
本文将会通过自定义 Bigraph 布局的例子讲解自定义布局。
@ -97,12 +97,12 @@ const data = {
- Step 1 `'part1'` 和 `'part2'` 的节点初始化随机序号 index都分别从 0 开始;
- Step 2遍历 `'part1'` 的节点,对每一个节点 A
- 找到与 A 相连的属于 `'part2'` 的节点的集合 ![]( https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-WOhQIGg9l8AAAAAAAAAAABkARQnAQ),加和 ![]( https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-WOhQIGg9l8AAAAAAAAAAABkARQnAQ) 中所有节点的 index并除以 ![]( https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-WOhQIGg9l8AAAAAAAAAAABkARQnAQ) 的元素个数,得数覆盖 A 的 index 值:![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*VfXiSK1f02cAAAAAAAAAAABkARQnAQ)
- Step 3遍历 `'part1'` 的节点,对每一个节点 B Step 2 相似):
- 找到与 B 相连的属于 `'part2'` 的节点的集合 ![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GqZiSKI-nB8AAAAAAAAAAABkARQnAQ),加和 ![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GqZiSKI-nB8AAAAAAAAAAABkARQnAQ) 中所有节点的 index并除以 ![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GqZiSKI-nB8AAAAAAAAAAABkARQnAQ) 的元素个数,得数覆盖 B 的 index 值:![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-8b2Spfb4HIAAAAAAAAAAABkARQnAQ)
- Step 3遍历 `'part2'` 的节点,对每一个节点 B Step 2 相似):
- 找到与 B 相连的属于 `'part1'` 的节点的集合 ![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GqZiSKI-nB8AAAAAAAAAAABkARQnAQ),加和 ![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GqZiSKI-nB8AAAAAAAAAAABkARQnAQ) 中所有节点的 index并除以 ![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GqZiSKI-nB8AAAAAAAAAAABkARQnAQ) 的元素个数,得数覆盖 B 的 index 值:![](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*-8b2Spfb4HIAAAAAAAAAAABkARQnAQ)
- Step 4两部分节点分别按照节点的序号 index 进行排序,最终按照节点顺序安排节点位置。
## 实现
下面代码展示了自定义名为 `'bigraph-layout'` 的二分图布局,完整代码参见:[自定义布局-二分图](/zh/examples/net/layoutMechanism#customBigraph)。使用该布局的方式与使用内置布局方式相同,都是在实例化图时将其配置到 `layout` 配置项中,详见:[使用布局 Layout](/zh/docs/manual/middle/layout)。
下面代码展示了自定义名为 `'bigraph-layout'` 的二分图布局,完整代码参见:<a href='/zh/examples/net/layoutMechanism#customBigraph' target='_blank'>自定义布局-二分图</a>。使用该布局的方式与使用内置布局方式相同,都是在实例化图时将其配置到 `layout` 配置项中,详见:[使用布局 Layout](/zh/docs/manual/middle/layout)。
```javascript
G6.registerLayout('bigraph-layout', {
@ -111,7 +111,7 @@ G6.registerLayout('bigraph-layout', {
return {
center: [0, 0], // 布局的中心
biSep: 100, // 两部分的间距
nodeSep: 20, // 同一部分的节点艰巨
nodeSep: 20, // 同一部分的节点间距
direction: 'horizontal', // 两部分的分布方向
nodeSize: 20 // 节点大小
};

View File

@ -1,26 +1,31 @@
---
title: 自定义节点
title: Custom Node
order: 2
---
G6 提供了一系列[内置节点](/zh/docs/manual/middle/elements/defaultNode),包括 [circle](/zh/docs/manual/middle/elements/nodes/circle)、[rect](https://www.yuque.com/antv/g6/vdqpdt)、[ellipse](/zh/docs/manual/middle/elements/nodes/ellipse)、[diamond](/zh/docs/manual/middle/elements/nodes/diamond)、[triangle](/zh/docs/manual/middle/elements/nodes/triangle)、[star](/zh/docs/manual/middle/elements/nodes/star)、[image](/zh/docs/manual/middle/elements/nodes/image)、[modelRect](/zh/docs/manual/middle/elements/nodes/modelRect)。若内置节点无法满足需求,用户还可以通过 `G6.registerNode('nodeName', options)` 进行自定义节点,方便用户开发更加定制化的节点,包括含有复杂图形的节点、复杂交互的节点、带有动画的节点等。
G6 provides abundant [Built-in Nodes](/en/docs/manual/middle/elements/nodes/defaultNode), including [circle](/en/docs/manual/middle/elements/nodes/circle), [rect](/en/docs/manual/middle/elements/nodes/rect, [ellipse](/en/docs/manual/middle/elements/nodes/ellipse), [diamond](/en/docs/manual/middle/elements/nodes/diamond), [triangle](/en/docs/manual/middle/elements/nodes/triangle), [star](/en/docs/manual/middle/elements/nodes/star), [image](/en/docs/manual/middle/elements/nodes/image), [modelRect](/en/docs/manual/middle/elements/nodes/modelRect). Besides, the custom machanism allows the users to design their own type of nodes by `G6.registerNode('nodeName', options)`. A node with complex graphics shapes, complex interactions, fantastic animations can be implemented easily.
在本章中我们会通过四个案例,从简单到复杂讲解节点的自定义。这四个案例是:
<br />
<strong>1. 从无到有的定义节点:</strong>绘制图形;优化性能。
<br />
<strong>2. 扩展现有的节点:</strong>附加图形;增加动画。
<br />
<strong>3. 调整节点的锚点;</strong>
<br />
<strong>4. 调整节点的鼠标选中/悬浮样式。</strong>样式变化响应;动画响应。
In this document, we will introduce the custom enodeby four examples:
<br />1. Register a bran-new edge;
<br />2. Register an edge by extending a built-in edge;
<br />3. Register an edge with interactions and styles;
<br />4. Register an edge with custom arrow.
通过 [图形 Shape](/zh/docs/manual/middle/keyConcept) 章节的学习,我们应该已经知道了自定义节点时需要满足以下两点:
<br />
<strong>1. Register a bran-new node: </strong>Draw the graphics; Optimize the performance.
<br />
<strong>2. Register a node by extending a built-in node: </strong>Add extra graphics shape; Add animation.
<br />
<strong>3. Adjust the anchorPoints(link points);</strong>
<br />
<strong>4. Register a node with state styles: </strong>Response the states change by styles and animations
- 控制节点的生命周期;
- 解析用户输入的数据,在图形上展示。
As stated in [Shape](/en/docs/manual/middle/keyconcept/shape-keyshape), there are two points should be satisfied when customize a node:
G6 中自定义节点的 API 如下:
- Controll the life cycle of the node;
- Analyze the input data and show it by graphics.
The API of cumstom node:
```javascript
G6.registerNode('nodeName', {
options: {
@ -31,83 +36,83 @@ G6.registerNode('nodeName', {
}
},
/**
* 绘制节点/边,包含文本
* @param {Object} cfg 节点的配置项
* @param {G.Group} group 节点的容器
* @return {G.Shape} 绘制的图形通过node.get('keyShape') 可以获取到
* Draw the node with label
* @param {Object} cfg The configurations of the node
* @param {G.Group} group The container of the node
* @return {G.Shape} The keyShape of the node. It can be obtained by node.get('keyShape')
*/
draw(cfg, group) {},
/**
* 绘制后的附加操作,默认没有任何操作
* @param {Object} cfg 节点的配置项
* @param {G.Group} group 节点的容器
* The extra operations after drawing the node. There is no operation in this function by default
* @param {Object} cfg The configurations of the node
* @param {G.Group} group The container of the node
*/
afterDraw(cfg, group) {},
/**
* 更新节点,包含文本
* Update the node and its label
* @override
* @param {Object} cfg 节点的配置项
* @param {Node} node 节点
* @param {Object} cfg The configurations of the node
* @param {Node} node The node item
*/
update(cfg, node) {},
/**
* 更新节点后的操作,一般同 afterDraw 配合使用
* The operations after updating the node. It is combined with afterDraw generally
* @override
* @param {Object} cfg 节点的配置项
* @param {Node} node 节点
* @param {Object} cfg The configurations of the node
* @param {Node} node The node item
*/
afterUpdate(cfg, node) {},
/**
* 设置节点的状态,主要是交互状态,业务状态请在 draw 方法中实现
* 单图形的节点仅考虑 selected、active 状态,有其他状态需求的用户自己复写这个方法
* @param {String} name 状态名称
* @param {Object} value 状态值
* @param {Node} node 节点
* Response the node states change. Mainly the interaction states. The business states should be handled in the draw function
* The states 'selected' and 'active' will be responsed on keyShape by default. To response more states, implement this function.
* @param {String} name The name of the state
* @param {Object} value The value of the state
* @param {Node} node The node item
*/
setState(name, value, node) {},
/**
* 获取控制点
* @param {Object} cfg 节点、边的配置项
* @return {Array|null} 控制点的数组,如果为 null则没有控制点
* Get the anchorPoints(link points for related edges)
* @param {Object} cfg The configurations of the node
* @return {Array|null} The array of anchorPoints(link points for related edges). Null means there are no anchorPoints
*/
getAnchorPoints(cfg) {}
}, extendNodeName);
```
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;注意:</span>
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;<strong>Attention:</strong> </span>
- 如果不从任何现有的节点扩展新节点时,`draw` 方法是必须的;
- `update` 方法可以不定义,数据更新时会走 draw 方法,所有图形清除重绘;
- `afterDraw``afterUpdate` 方法一般用于扩展已有的节点/和边,例如:在矩形上附加图片,线上增加动画等;
- `setState` 方法一般也不需要复写,有全局的样式可以替换;
- `getAnchorPoints` 方法仅在需要限制与边的连接点时才需要复写,也可以在数据中直接指定。
- `draw` is required if the custom node does not extend any parent;
- `update` is not required. If it is undefined, the `draw` will be called when updating the node, which means all the graphics will be cleared and repaint;
- `afterDraw` and `afterUpdate` are used for extending the exited nodes in general. e.g. adding extra image on rect node, adding animation on a circle node, ...;
- In general, `setState` is not required;
- `getAnchorPoints` is only required when you want to contrain the link points for nodes and their related edges. The anchorPoints can be assigned in the node data as well.
## 1. 从无到有定义节点
### 绘制图形
我们自己来实现一个菱形的节点,如下图所示。
> G6 有内置的菱形节点 diamond。为了演示这里实现了一个自定义的菱形相当于复写了内置的 diamond。
## 1. Register a Bran-new Edge
### Render the Node
Now, we are going to register a diamond node:
> Although there is a built-in diamond node in G6, we implement it here to rewrite it for demonstration.
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*LqFCRaKyr0gAAAAAAAAAAABkARQnAQ' alt='img' width='80'/>
```javascript
G6.registerNode('diamond', {
draw(cfg, group) {
// 如果 cfg 中定义了 style 需要同这里的属性进行融合
// If there is style object in cfg, it should be mixed here
const shape = group.addShape('path', {
attrs: {
path: this.getPath(cfg), // 根据配置获取路径
stroke: cfg.color // 颜色应用到边上,如果应用到填充,则使用 fill: cfg.color
path: this.getPath(cfg), // Get the path by cfg
stroke: cfg.color // Apply the color to the stroke. For filling, use fill: cfg.color instead
}
});
if(cfg.label) { // 如果有文本
// 如果需要复杂的文本配置项,可以通过 labeCfg 传入
if(cfg.label) { // If the label exists
// The complex label configurations can be defined by labeCfg
// const style = (cfg.labelCfg && cfg.labelCfg.style) || {};
// style.text = cfg.label;
group.addShape('text', {
// attrs: style
attrs: {
x: 0, // 居中
x: 0, // center
y: 0,
textAlign: 'center',
textBaseline: 'middle',
@ -118,34 +123,34 @@ G6.registerNode('diamond', {
}
return shape;
},
// 返回菱形的路径
// Return the path of a diamond
getPath(cfg) {
const size = cfg.size || [40, 40]; // 如果没有 size 时的默认大小
const size = cfg.size || [40, 40];
const width = size[0];
const height = size[1];
// / 1 \
// 4 2
// \ 3 /
const path = [
['M', 0, 0 - height / 2], // 上部顶点
['L', width / 2, 0], // 右侧顶点
['L', 0, height / 2], // 下部顶点
['L', - width / 2, 0], // 左侧顶点
['Z'] // 封闭
['M', 0, 0 - height / 2], // Top
['L', width / 2, 0], // Right
['L', 0, height / 2], // Bottom
['L', - width / 2, 0], // Left
['Z'] // Close the path
];
return path;
},
});
```
上面的代码自定义了一个菱形节点,然后我们使用下面的数据输入就会绘制出 diamond 这个节点。
We have registered a dimond node. The following code use the diamond node:
```javascript
const data = {
nodes: [
{x: 50, y: 100, shape: 'diamond'}, // 最简单的
{x: 150, y: 100, shape: 'diamond', size: [50, 100]}, // 添加宽高
{x: 250, y: 100, color: 'red', shape: 'diamond'}, // 添加颜色
{x: 350, y: 100, label: '菱形', shape: 'diamond'} // 附加文本
{x: 50, y: 100, shape: 'diamond'}, // The simplest form
{x: 150, y: 100, shape: 'diamond', size: [50, 100]}, // Add the size
{x: 250, y: 100, color: 'red', shape: 'diamond'}, // Add the color
{x: 350, y: 100, label: '菱形', shape: 'diamond'} // Add the label
]
};
const graph = new G6.Graph({
@ -159,49 +164,47 @@ graph.render();
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*qv88SrrnmFAAAAAAAAAAAABkARQnAQ' alt='img' width='300'/>
### 优化性能
当图中节点或边通过 `graph.update(item, cfg)` 重绘时,默认情况下会调用节点的 `draw` 方法进行重新绘制。在数据量大或节点上图形数量非常多(特别是文本多)的情况下,`draw` 方法中对所有图形、赋予样式将会非常消耗性能。
### Optimize the Performance
When the nodes or edges are updated by `graph.update(item, cfg)`, the `draw` will be called for repainting. But in the situation with large amount of data (especially the text), repainting all the graphics shapes by `draw` has bad performance.
在自定义节点时,重写 `update` 方法,在更新时将会调用该方法替代 `draw`。我们可以在该方法中指定需要更新的图形,从而避免频繁调用 `draw` 、全量更新节点上的所有图形。当然,`update` 方法是可选的,如果没有性能优化的需求可以不重写该方法。
Therefore, rewrite the `update` function when registering a node for partial repainting is necessary. We can repaint some of the graphics shapes instead of all the graphis by `update`. The `update` is not required if you have no performance problem.
在实现 diamond 的过程中,重写 `update` 方法,找到需要更新的 shape 进行更新,从而优化性能。寻找需要更新的图形可以通过:
To update a few graphics shapes of a node in `update`, you need find the graphics shapes to be updated frist:
- `group.get('children')[0]` 找到 [关键图形 keyShape](/zh/docs/manual/middle/keyConcept),也就是 `draw` 方法返回的 shape
- `group.get('children')[1]` 找到 label 图形。
- Find the [keyShape](/en/docs/manual/middle/keyconcept/shape-keyshape#keyshape) by `group.get('children')[0]`, which is the return value of `draw`;
- Find the graphics shape of label by `group.get('children')[1]`.
下面代码仅更新了 diamond 的关键图形的路径和颜色。
The code shown below update the path and the color of the keyShape of the diamond:
```javascript
G6.registerNode('diamond', {
draw(cfg, group) {
// ... // 见前面代码
// ... // Same as the code above
},
getPath(cfg) {
// ... // 见前面代码
// ... // Same as the code above
},
update(cfg, node) {
const group = node.getContainer(); // 获取容器
const shape = group.get('children')[0]; // 按照添加的顺序
const group = node.getContainer(); // Get the container of the node
const shape = group.get('children')[0]; // Find the first graphics shape of the node. It is determined by the order of being added
const style = {
path: this.getPath(cfg),
stroke: cfg.color
};
shape.attr(style); // 更新属性
// 更新文本的逻辑类似,但是需要考虑 cfg.label 是否存在的问题
// 通过 label.attr() 更新文本属性即可
shape.attr(style); // Update
}
});
```
## 2. 扩展现有节点
### 扩展 Shape
G6 中已经[内置了一些节点](/zh/docs/manual/middle/elements/defaultNode),如果用户仅仅想对现有节点进行调整,复用原有的代码,则可以基于现有的节点进行扩展。同样实现 diamond 可以基于 circle、ellipse、rect 等内置节点的进行扩展。[simple-shape](https://github.com/antvis/g6/blob/master/src/shape/single-shape-mixin.js) 是这些内置节点图形的基类,也可以基于它进行扩展。
## 2. Extend a Built-in Node
### Extend the Shape
There are several [Built-in Nodes](/en/docs/manual/middle/elements/nodes/defaultNode) in G6. You can extend them to make some modification on them. It is similar to register the diamond node. <a href='https://github.com/antvis/g6/blob/master/src/shape/single-shape-mixin.js' target='_blank'>single-shape</a> is the base class of all the graphics shape, you can also extend it.
下面以基于 single-shape 为例进行扩展。`draw``update``setState` 方法在 [simple-shape ](https://github.com/antvis/g6/blob/master/src/shape/single-shape-mixin.js)中都有实现,这里仅需要复写 `getShapeStyle` 方法即可。返回的对象中包含自定义图形的路径和其他样式。
For example, we are going to extend the single-shape. `draw`, `update`, and `setState` have been implemented in the <a href='https://github.com/antvis/g6/blob/master/src/shape/single-shape-mixin.js' target='_blank'>single-shape</a>. Thus, we only rewrite the `getShapeStyle`, which returns the path and the styles of graphics shapes.
```javascript
G6.registerNode('diamond', {
shapeType: 'path', // group.addShape 时需要指定的类型
shapeType: 'path', // It is required when the shape inherits from 'single-shape', not required otherwise
getShapeStyle(cfg) {
const size = this.getSize(cfg); // 转换成 [width, height] 的模式
const size = this.getSize(cfg); // translate to [width, height]
const color = cfg.color;
const width = size[0];
const height = size[1];
@ -209,11 +212,11 @@ G6.registerNode('diamond', {
// 4 2
// \ 3 /
const path = [
['M', 0, 0 - height / 2], // 上部顶点
['L', width / 2, 0], // 右侧顶点
['L', 0, height / 2], // 下部顶点
['L', - width / 2, 0], // 左侧顶点
['Z'] // 封闭
['M', 0, 0 - height / 2], // Top
['L', width / 2, 0], // Right
['L', 0, height / 2], // Bottom
['L', - width / 2, 0], // Left
['Z'] // Close the path
];
const style = Util.mix({}, {
path: path,
@ -222,27 +225,25 @@ G6.registerNode('diamond', {
return style;
}
},
// 注意这里继承了 'single-shape'
// Extend the 'single-shape'
'single-shape');
```
### 添加动画
通过 `afterDraw` 同样可以实现扩展,下面我们来看一个节点的动画场景,如下图所示。<br />
### Add Animation
We are going to add animation by `afterDraw` in this section. The result:<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*ga7FQLdUYjkAAAAAAAAAAABkARQnAQ' alt='img' width='350'/>
上面的动画效果,可以通过以下方式实现:
- 扩展内置的 rect在 rect 中添加一个图形;
- 反复执行新添加图形的旋转动画。
- Extend the built-in rect node, and add a graphics shape in the rect;
- Execute the animation repeatly.
```javascript
// 自定义一个名为 inner-animate 的节点
// Register a type of custom node named inner-animate
G6.registerNode('inner-animate', {
afterDraw(cfg, group) {
const size = cfg.size;
const width = size[0] - 14;
const height = size[1] - 14;
// 添加图片
// Add an image shape
const image = group.addShape('image', {
attrs: {
x: - width / 2,
@ -252,49 +253,50 @@ G6.registerNode('inner-animate', {
img: cfg.img
}
});
// 执行旋转动画
image.animate({
onFrame(ratio) {
const matrix = Util.mat3.create();
const toMatrix = Util.transform(matrix, [
['r', ratio * Math.PI * 2]
]) ;
return {
matrix: toMatrix
};
},
repeat: true
}, 3000, 'easeCubic');
// Execute the animation
image.animate((ratio) => {
const matrix = Util.mat3.create();
const toMatrix = Util.transform(matrix, [
['r', ratio * Math.PI * 2]
]) ;
return {
matrix: toMatrix
};
}, {
repeat: true,
duration: 3000,
easing: 'easeCubic'
});
}
},
// 继承了 rect 节点
// Extend the rect node
'rect');
```
更多关于动画的实现,请参考[基础动画](/zh/docs/manual/advanced/animation)章节。
For more information about animation, please refer to [Basic Ainmation](/en/docs/manual/advanced/animation).
<br />
## 3. 调整锚点 anchorPoint
节点上的[锚点 anchorPoint](/zh/docs/manual/middle/keyConcept) 作用是**确定节点与边的相交的位置**,看下面的场景:<br />
## 3. Adjust the anchorPoint
The [anchorPoint](/en/docs/manual/middle/keyconcept/anchorpoint) of a node is **the intersection of the node and its related edges**.<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*mJ85Q5WRJLwAAAAAAAAAAABkARQnAQ' alt='img' width='200'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*99aSR5zbd44AAAAAAAAAAABkARQnAQ' alt='img' width='200'/>
> 没有设置锚点时。diamond 设置了锚点后。
> (Left) The diamond node has no anchorPoints. (Right) The diamond node has anchorPoints.
有两种方式来调整节点上的锚点:
There are two ways to adjust the anchorPoints of the node:
- 在数据里面指定 `anchorPoints`
- Configure the `anchorPoints` in the data.
      **适用场景:**可以为不同节点配置不同的锚点,更定制化。
      **Applicable Scene:** Assign different anchorPoints for different nodes.
- 自定义节点中通过 `getAnchorPoints` 方法指定锚点。
- Assign `getAnchorPoints` when registering a custom node.
      **适用场景:**全局配置锚点,所有该自定义节点类型的节点都相同。
      **Applicable Scene:** Configure the anchorPoints globally for this type of node.
### 数据中指定锚点
### Configure the anchorPoints in Data
```javascript
const data = {
nodes: [{
@ -302,49 +304,49 @@ const data = {
x: 100,
y: 100,
anchorPoints: [
[0, 0.5], // 左侧中间
[1, 0.5] // 右侧中间
[0, 0.5], // The center of the left border
[1, 0.5] // The center of the right border
]},
//... // 其他节点
//... // Other nodes
],
edges: [
//... //
//... // Other edges
]
};
```
### 自定义时指定锚点
### Assign anchorPoints When Registering Node
```javascript
G6.registerNode('diamond', {
//... // 其他方法
//... // Other functions
getAnchorPoints() {
return [
[0, 0.5], // 左侧中间
[1, 0.5] // 右侧中间
[0, 0.5], // The center of the left border
[1, 0.5] // The center of the right border
]
}
}, 'rect');
```
## 4. 调整状态样式
常见的交互都需要节点和边通过样式变化做出反馈,例如鼠标移动到节点上、点击选中节点/边、通过交互激活边上的交互等,都需要改变节点和边的样式,有两种方式来实现这种效果:
## 4. Register Node with State Styles
In general, nodes and edges should response the states change by styles chaging. For example, highlight the node or edge clicked/hovered by user. We can achieve it by two ways:
1. 在数据上添加标志字段,在自定义 shape 过程中根据约定进行渲染;
1. 将交互状态同原始数据和绘制节点的逻辑分开,仅更新节点。
1. Add a flag on the node data, control the style according to the flag in `draw` when registering a custom node;
2. Separate the interactive states from source data and `draw`, update the node only.
我们推荐用户使用第二种方式来实现节点的状态调整,可以通过以下方式来实现:
We recommend adjust the state styles by the second way, which can be achieved by:
- 在 G6 中自定义节点/边时在 `setState` 方法中进行节点状态的设置;
- 通过 `graph.setItemState()` 方法来设置状态。
- Response the states in `setState` function when registering a node/edge;
- Set/change the state by `graph.setItemState()`.
基于 rect 扩展出一个 custom 图形,默认填充色为白色,当鼠标点击时变成红色,实现这一效果的示例代码如下:
Based on rect node, we extend a custom node with white filling. It will be turned to red when the mouse clicks it. Implement it by the code below:
```javascript
// 基于 rect 扩展出新的图形
// Extend rect
G6.registerNode('custom', {
// 设置状态
// Response the states
setState(name, value, item) {
const group = item.getContainer();
const shape = group.get('children')[0]; // 顺序根据 draw 时确定
const shape = group.get('children')[0]; // Find the first graphics shape of the node. It is determined by the order of being added
if(name === 'selected') {
if(value) {
shape.attr('fill', 'red');
@ -355,28 +357,30 @@ G6.registerNode('custom', {
}
}, 'rect');
// 点击时选中,再点击时取消
// Click to select, cancel by clicking again
graph.on('node:click', ev=> {
const node = ev.item;
graph.setItemState(node, 'selected', !node.hasState('selected')); // 切换选中
graph.setItemState(node, 'selected', !node.hasState('selected')); // Switch the selected state
});
```
G6 并未限定节点的状态,只要你在 `setState` 方法中进行处理你可以实现任何交互,如实现鼠标放到节点上后节点逐渐变大的效果。<br />
G6 does not limit the states for nodes/edges, you can assign any states to a node once you response it in the `setState` function. e.g. magnify the node by hovering:<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*JhhTSJ8PMbYAAAAAAAAAAABkARQnAQ' alt='img' width='350'/>
```javascript
G6.registerNode('custom', {
// 设置状态
// Response the states change
setState(name, value, item) {
const group = item.getContainer();
const shape = group.get('children')[0]; // 顺序根据 draw 时确定
const shape = group.get('children')[0]; // Find the first graphics shape of the node. It is determined by the order of being added
if(name === 'running') {
if(value) {
shape.animate({
r: 20,
repeat: true
}, 1000);
r: 20
}, {
repeat: true,
duration: 1000
});
} else {
shape.stopAnimate();
shape.attr('r', 10);
@ -385,7 +389,7 @@ G6.registerNode('custom', {
}
}, 'circle');
// 鼠标移动到上面 running移出结束
// Activate 'running' by mouse entering. Turn it of by mouse leaving.
graph.on('node:mouseenter', ev=> {
const node = ev.item;
graph.setItemState(node, 'running', true);

View File

@ -3,7 +3,7 @@ title: 自定义节点
order: 2
---
G6 提供了一系列[内置节点](/zh/docs/manual/middle/elements/defaultNode),包括 [circle](/zh/docs/manual/middle/elements/nodes/circle)、[rect](https://www.yuque.com/antv/g6/vdqpdt)、[ellipse](/zh/docs/manual/middle/elements/nodes/ellipse)、[diamond](/zh/docs/manual/middle/elements/nodes/diamond)、[triangle](/zh/docs/manual/middle/elements/nodes/triangle)、[star](/zh/docs/manual/middle/elements/nodes/star)、[image](/zh/docs/manual/middle/elements/nodes/image)、[modelRect](/zh/docs/manual/middle/elements/nodes/modelRect)。若内置节点无法满足需求,用户还可以通过 `G6.registerNode('nodeName', options)` 进行自定义节点,方便用户开发更加定制化的节点,包括含有复杂图形的节点、复杂交互的节点、带有动画的节点等。
G6 提供了一系列[内置节点](/zh/docs/manual/middle/elements/nodes/defaultNode),包括 [circle](/zh/docs/manual/middle/elements/nodes/circle)、[rect](/zh/docs/manual/middle/elements/nodes/rect)、[diamond](/zh/docs/manual/middle/elements/nodes/diamond)、[triangle](/zh/docs/manual/middle/elements/nodes/triangle)、[star](/zh/docs/manual/middle/elements/nodes/star)、[image](/zh/docs/manual/middle/elements/nodes/image)、[modelRect](/zh/docs/manual/middle/elements/nodes/modelRect)。若内置节点无法满足需求,用户还可以通过 `G6.registerNode('nodeName', options)` 进行自定义节点,方便用户开发更加定制化的节点,包括含有复杂图形的节点、复杂交互的节点、带有动画的节点等。
在本章中我们会通过四个案例,从简单到复杂讲解节点的自定义。这四个案例是:
<br />
@ -15,7 +15,7 @@ G6 提供了一系列[内置节点](/zh/docs/manual/middle/elements/defaultNode)
<br />
<strong>4. 调整节点的鼠标选中/悬浮样式。</strong>样式变化响应;动画响应。
通过 [图形 Shape](/zh/docs/manual/middle/keyConcept) 章节的学习,我们应该已经知道了自定义节点时需要满足以下两点:
通过 [图形 Shape](/zh/docs/manual/middle/keyconcept/shape-keyshape) 章节的学习,我们应该已经知道了自定义节点时需要满足以下两点:
- 控制节点的生命周期;
- 解析用户输入的数据,在图形上展示。
@ -31,10 +31,10 @@ G6.registerNode('nodeName', {
}
},
/**
* 绘制节点/边,包含文本
* 绘制节点,包含文本
* @param {Object} cfg 节点的配置项
* @param {G.Group} group 节点的容器
* @return {G.Shape} 绘制的图形通过node.get('keyShape') 可以获取到
* @return {G.Shape} 绘制的图形,通过 node.get('keyShape') 可以获取到
*/
draw(cfg, group) {},
/**
@ -58,27 +58,27 @@ G6.registerNode('nodeName', {
*/
afterUpdate(cfg, node) {},
/**
* 设置节点的状态,主要是交互状态,业务状态请在 draw 方法中实现
* 单图形的节点仅考虑 selected、active 状态,有其他状态需求的用户自己复写这个方法
* 响应节点的状态变化,主要是交互状态,业务状态请在 draw 方法中实现
* 默认情况下,节点的 keyShape 将会响应 selected、active 状态,有其他状态需求的用户自己复写这个方法
* @param {String} name 状态名称
* @param {Object} value 状态值
* @param {Node} node 节点
*/
setState(name, value, node) {},
/**
* 获取控制点
* @param {Object} cfg 节点、边的配置项
* @return {Array|null} 控制点的数组,如果为 null则没有控制点
* 获取锚点(相关边的连入点)
* @param {Object} cfg 节点的配置项
* @return {Array|null} 锚点(相关边的连入点)的数组,如果为 null则没有控制点
*/
getAnchorPoints(cfg) {}
}, extendNodeName);
```
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;注意:</span>
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;<strong>⚠️注意:</strong></span>
- 如果不从任何现有的节点扩展新节点时,`draw` 方法是必须的;
- `update` 方法可以不定义,数据更新时会走 draw 方法,所有图形清除重绘;
- `afterDraw``afterUpdate` 方法一般用于扩展已有的节点/和边,例如:在矩形上附加图片,线上增加动画等;
- `update` 方法可以不定义,数据更新时会走 `draw` 方法,所有图形清除重绘;
- `afterDraw``afterUpdate` 方法一般用于扩展已有的节点,例如:在矩形节点上附加图片,圆节点增加动画等;
- `setState` 方法一般也不需要复写,有全局的样式可以替换;
- `getAnchorPoints` 方法仅在需要限制与边的连接点时才需要复写,也可以在数据中直接指定。
@ -97,7 +97,7 @@ G6.registerNode('diamond', {
const shape = group.addShape('path', {
attrs: {
path: this.getPath(cfg), // 根据配置获取路径
stroke: cfg.color // 颜色应用到边上,如果应用到填充,则使用 fill: cfg.color
stroke: cfg.color // 颜色应用到边上,如果应用到填充,则使用 fill: cfg.color
}
});
if(cfg.label) { // 如果有文本
@ -166,7 +166,7 @@ graph.render();
在实现 diamond 的过程中,重写 `update` 方法,找到需要更新的 shape 进行更新,从而优化性能。寻找需要更新的图形可以通过:
- `group.get('children')[0]` 找到 [关键图形 keyShape](/zh/docs/manual/middle/keyConcept),也就是 `draw` 方法返回的 shape
- `group.get('children')[0]` 找到 [关键图形 keyShape](/zh/docs/manual/middle/keyconcept/shape-keyshape#keyshape),也就是 `draw` 方法返回的 shape
- `group.get('children')[1]` 找到 label 图形。
下面代码仅更新了 diamond 的关键图形的路径和颜色。
@ -194,12 +194,12 @@ G6.registerNode('diamond', {
## 2. 扩展现有节点
### 扩展 Shape
G6 中已经[内置了一些节点](/zh/docs/manual/middle/elements/defaultNode),如果用户仅仅想对现有节点进行调整,复用原有的代码,则可以基于现有的节点进行扩展。同样实现 diamond 可以基于 circle、ellipse、rect 等内置节点的进行扩展。[simple-shape](https://github.com/antvis/g6/blob/master/src/shape/single-shape-mixin.js) 是这些内置节点图形的基类,也可以基于它进行扩展。
G6 中已经[内置了一些节点](/zh/docs/manual/middle/elements/nodes/defaultNode),如果用户仅仅想对现有节点进行调整,复用原有的代码,则可以基于现有的节点进行扩展。同样实现 diamond 可以基于 circle、ellipse、rect 等内置节点的进行扩展。<a href='https://github.com/antvis/g6/blob/master/src/shape/single-shape-mixin.js' target='_blank'>single-shape</a> 是这些内置节点图形的基类,也可以基于它进行扩展。
下面以基于 single-shape 为例进行扩展。`draw``update``setState` 方法在 [simple-shape ](https://github.com/antvis/g6/blob/master/src/shape/single-shape-mixin.js)中都有实现,这里仅需要复写 `getShapeStyle` 方法即可。返回的对象中包含自定义图形的路径和其他样式。
下面以基于 single-shape 为例进行扩展。`draw``update``setState` 方法在 <a href='https://github.com/antvis/g6/blob/master/src/shape/single-shape-mixin.js' target='_blank'>single-shape</a> 中都有实现,这里仅需要复写 `getShapeStyle` 方法即可。返回的对象中包含自定义图形的路径和其他样式。
```javascript
G6.registerNode('diamond', {
shapeType: 'path', // group.addShape 时需要指定的类型
shapeType: 'path', // 继承自 'single-shape' 时必须指定,否则不需要填写
getShapeStyle(cfg) {
const size = this.getSize(cfg); // 转换成 [width, height] 的模式
const color = cfg.color;
@ -253,18 +253,19 @@ G6.registerNode('inner-animate', {
}
});
// 执行旋转动画
image.animate({
onFrame(ratio) {
const matrix = Util.mat3.create();
const toMatrix = Util.transform(matrix, [
['r', ratio * Math.PI * 2]
]) ;
return {
matrix: toMatrix
};
},
image.animate((ratio) => {
const matrix = Util.mat3.create();
const toMatrix = Util.transform(matrix, [
['r', ratio * Math.PI * 2]
]) ;
return {
matrix: toMatrix
};
}, {
repeat: true
}, 3000, 'easeCubic');
duration: 3000,
easing: 'easeCubic'
});
}
},
// 继承了 rect 节点
@ -276,7 +277,7 @@ G6.registerNode('inner-animate', {
<br />
## 3. 调整锚点 anchorPoint
节点上的[锚点 anchorPoint](/zh/docs/manual/middle/keyConcept) 作用是**确定节点与边的相交的位置**,看下面的场景:<br />
节点上的[锚点 anchorPoint](/zh/docs/manual/middle/keyconcept/anchorpoint) 作用是**确定节点与边的相交的位置**,看下面的场景:<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*mJ85Q5WRJLwAAAAAAAAAAABkARQnAQ' alt='img' width='200'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*99aSR5zbd44AAAAAAAAAAABkARQnAQ' alt='img' width='200'/>
@ -330,18 +331,18 @@ G6.registerNode('diamond', {
常见的交互都需要节点和边通过样式变化做出反馈,例如鼠标移动到节点上、点击选中节点/边、通过交互激活边上的交互等,都需要改变节点和边的样式,有两种方式来实现这种效果:
1. 在数据上添加标志字段,在自定义 shape 过程中根据约定进行渲染;
1. 将交互状态同原始数据和绘制节点的逻辑分开,仅更新节点。
2. 将交互状态同原始数据和绘制节点的逻辑分开,仅更新节点。
我们推荐用户使用第二种方式来实现节点的状态调整,可以通过以下方式来实现:
- 在 G6 中自定义节点/边时在 `setState` 方法中进行节点状态的设置
- 在 G6 中自定义节点/边时在 `setState` 方法中进行节点状态变化的响应
- 通过 `graph.setItemState()` 方法来设置状态。
基于 rect 扩展出一个 custom 图形,默认填充色为白色,当鼠标点击时变成红色,实现这一效果的示例代码如下:
```javascript
// 基于 rect 扩展出新的图形
G6.registerNode('custom', {
// 设置状态
// 响应状态变化
setState(name, value, item) {
const group = item.getContainer();
const shape = group.get('children')[0]; // 顺序根据 draw 时确定
@ -367,16 +368,18 @@ G6 并未限定节点的状态,只要你在 `setState` 方法中进行处理
```javascript
G6.registerNode('custom', {
// 设置状态
// 响应状态变化
setState(name, value, item) {
const group = item.getContainer();
const shape = group.get('children')[0]; // 顺序根据 draw 时确定
if(name === 'running') {
if(value) {
shape.animate({
r: 20,
repeat: true
}, 1000);
r: 20
}, {
repeat: true,
duration: 1000
});
} else {
shape.stopAnimate();
shape.attr('r', 10);

View File

@ -1,64 +0,0 @@
---
title: 关键概念-图形分组 Group
order: 1
---
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;注意:</span>
<br />图形分组 Group 与 [节点分组 Group](/zh/docs/manual/middle/nodeGroup) 虽然都名为 Group但属于不同层次的概念。
- 图形分组针对 [图形 Shape](/zh/docs/manual/middle/keyConcept) 层次的分组;
- [节点分组 Group](/zh/docs/manual/middle/nodeGroup) 是针对 [节点](/zh/docs/manual/middle/elements/defaultNode) 的分组,与数据结构中的层次、分组对应。
<br />
## 什么是图形分组 Group
图形分组 group 类似于 [SVG 中的 ](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g)[`<g>`](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g)[ 标签](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g):元素 `g` 是用来组合图形对象的容器。在 group 上添加变换例如剪裁、旋转、放缩、平移等会应用到其所有的子元素上。在 group 上添加属性例如颜色、位置等会被其所有的子元素继承。此外 group 可以多层嵌套使用,因此可以用来定义复杂的对象。
在 G6 中Graph 的一个实例中的所有节点属于同一个变量名为 `nodeGroup` 的 group所有的边属于同一个变量名为 `edgeGroup` 的 group。节点 group 在视觉上的层级zIndex高于边 group即所有节点会绘制在所有边的上层。<br />如下图(左)三个节点属于 `nodeGroup` ,两条边属于 `edgeGroup`  `nodeGroup` 层级高于 `edgeGroup` ,三个节点绘制在三条边的上层。下图(右)是(左)图的节点降低透明度后的效果,可以更清晰看到边绘制在节点下方。<br />
![image.png](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*oqKUSoRWMrcAAAAAAAAAAABkARQnAQ)![image.png](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*cudnTqD-g_4AAAAAAAAAAABkARQnAQ)
> (左)节点和边的图形分组 Group 演示。(右)给左图的节点降低了透明度。
## 何时使用图形分组 Group
[自定义节点](https://www.yuque.com/antv/g6/self-node)、[自定义边](https://www.yuque.com/antv/g6/self-edge)时将会涉及到图形分组 Group 的概念。图形分组 Group 方便了用户对节点或边上元素的组合和管理。<br />例如,如下图中的节点 A 有一个包含节点 A 中所有图形的 group该 group 中包含了一个 circle 图形和一个文本图形。节点 B 是一个自定义节点,有一个包含节点 B 中所有图形的 group该 group 包含了 circle 图形、rect 图形、文本图形。<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GnVoSIGkXhsAAAAAAAAAAABkARQnAQ' alt='img' width='100'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*iQXZTZCX9LEAAAAAAAAAAABkARQnAQ' alt='img' width='100'/>
<br />
## 如何使用图形分组 Group
以下方法将会在[自定义节点](/zh/docs/manual/advanced/custom-node)、[自定义边](/zh/docs/manual/advanced/custom-edge)时用到。
### 声明实例
```
const group = new Group(cfgs);
```
### 实例方法
- addGroup(cfgs)
向分组中添加新的分组。
```javascript
const subGroup = group.addGroup({
id: 'rect'
})
```
- addShape(type, cfgs)
向分组中添加新的图形。
```javascript
const keyShape = group.addShape('rect', {
attrs: {
stroke: 'red'
}
})
```
提示:在分组上添加的 `clip` `transform` 等会影响到该分组中的所有图形。

View File

@ -1,33 +1,33 @@
---
title: 使用 Iconfont
title: Utilizing Iconfont
order: 9
---
## 简介
为什么使用 iconfont 兼容性好、种类多、多色等。在此不做过多介绍请直接移步[阿里巴巴-iconfont平台](https://www.iconfont.cn)。
## Introduction
Due to the good compatibility, type diversity, color diversity, The iconfont is popupar for front-end developments now. Refer to the <a href='https://www.iconfont.cn' target='_blank'>Iconfont Library of Alibaba</a>.
## 效果
## Effect
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*rJ3lQa0HR-wAAAAAAAAAAABkARQnAQ' alt='result' width='450'/>
## 下载字体图标
直接去到[阿里巴巴字体图标库](https://www.iconfont.cn)搜索下载即可,简要操作流程是:搜索图标(例如篮球) ->  选择自己喜欢的图标添加入库  ->  点击页面右上角的购物车可以看到我们加入的图标 -> 添加至项目,如果没有项目到话可以新建一个  ->  在我到项目里面点击下载至本地 -> 解压。如果一切操作正常的话可以得到如下解压文件:<br />
## Download the iconfont
Browse the <a href='https://www.iconfont.cn' target='_blank'>Iconfont Library of Alibaba</a> and download the iconfont you like by searching a iconfont -> adding it to your library -> going to your library by clicking the shopping cart logo on the right top -> adding it to your project (new one if you do not have any project) -> downloading the iconfont in 'my project' -> decompressing. You will get the files as shown below if everything is right:<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*EnNmQ5m7xHUAAAAAAAAAAABkARQnAQ' alt='download' width='550'/>
选中红色区域的所有文件(这里面很多文件是不需要的,为了方便起见,我们全部复制即可,不需要的也不会被打包),复制到项目里面,一般放在目录 'static/icons' 或者 'assets/icons' 下面,如果没有的话可以新建目录,当然你也可以放到任意你喜欢的位置,只要引入的时候路径对即可,到此 iconfont 引入完毕。
Copy the files in the red area (there are lots of unecessary files, we can still copy them all since the unused files will not be packed)to your project. In general, the iconfont files are on the directory of 'static/icons' or 'assets/icons'. New the directory if there is no such directory. It is also fine to put them into any directory. But note to import the right path when you use it. Now, the importing process is done.
PS: 本案文件目录为 '/static/icons'
PS: The directory for this example is '/static/icons'.
## 引入G6
多种引入方式,请移步[快速上手](/zh/docs/manual/getting-started)。
<br />PS: 本案例简单粗暴通过CDN的方式引入。
## Import G6
There are several ways to import G6 introduced in [Getting Started](/en/docs/manual/getting-started).
<br />PS: We import G6 by CDN in this example.
```html
<script src="https://gw.alipayobjects.com/os/antv/pkg/_antv.g6-3.2.0/build/g6.js"></script>
```
## 添加字体图标
引入方式可自行选择,下面为在 HTML 中引入的例子:
## Import the Iconfont
We import the iconfont in HTML here:
```html
<style>
@ -35,84 +35,80 @@ PS: 本案文件目录为 '/static/icons'
</style>
```
## 使用字体
## Using Iconfont
```javascript
G6.registerNode("iconfont", {
G6.registerNode('iconfont', {
draw(cfg, group) {
const {
backgroundConfig: backgroundStyle,
style,
labelCfg: labelStyle
} = cfg;
const { backgroundConfig: backgroundStyle, style, labelCfg: labelStyle } = cfg;
if (backgroundStyle) {
group.addShape("circle", {
group.addShape('circle', {
attrs: {
x: 0,
y: 0,
r: cfg.size,
...backgroundStyle
}
...backgroundStyle,
},
});
}
const keyShape = group.addShape("text", {
const keyShape = group.addShape('text', {
attrs: {
x: 0,
y: 0,
fontFamily: "iconfont", // 对应css里面的font-family: "iconfont";
textAlign: "center",
textBaseline: "middle",
fontFamily: 'iconfont', // 对应css里面的font-family: "iconfont";
textAlign: 'center',
textBaseline: 'middle',
text: cfg.text,
fontSize: cfg.size,
...style
}
...style,
},
});
const labelY = backgroundStyle ? cfg.size * 2 : cfg.size;
group.addShape("text", {
group.addShape('text', {
attrs: {
x: 0,
y: labelY,
textAlign: "center",
textAlign: 'center',
text: cfg.label,
...labelStyle.style
}
...labelStyle.style,
},
});
return keyShape;
}
},
});
const COLOR = "#40a9ff";
const COLOR = '#40a9ff';
const graph = new G6.TreeGraph({
container: "mountNode",
container: 'mountNode',
width: 800,
height: 600,
modes: {
default: ["collapse-expand", "drag-canvas", "drag-node"]
default: ['collapse-expand', 'drag-canvas', 'drag-node'],
},
defaultNode: {
backgroundConfig: {
backgroundType: "circle",
backgroundType: 'circle',
fill: COLOR,
stroke: "LightSkyBlue"
stroke: 'LightSkyBlue',
},
shape: "iconfont",
shape: 'iconfont',
size: 12,
style: {
fill: "#fff"
fill: '#fff',
},
labelCfg: {
style: {
fill: COLOR,
fontSize: 12
}
}
fontSize: 12,
},
},
},
// 布局相关
layout: {
type: "compactBox",
direction: "LR",
type: 'compactBox',
direction: 'LR',
getId(d) {
return d.id;
},
@ -127,166 +123,205 @@ const graph = new G6.TreeGraph({
},
getHGap() {
return 60;
}
}
},
},
});
graph.edge(({ target }) => {
const fill =
target.get("model").backgroundConfig &&
target.get("model").backgroundConfig.fill;
const fill = target.get('model').backgroundConfig && target.get('model').backgroundConfig.fill;
return {
shape: "cubic-horizontal",
shape: 'cubic-horizontal',
color: fill || COLOR,
label: target.get("model").relation || "",
label: target.get('model').relation || '',
labelCfg: {
style: {
fill: fill || COLOR,
fontSize: 12
}
}
fontSize: 12,
},
},
};
});
const data = {
isRoot: true,
id: "Root",
label: "可疑人员王**",
text: "&#xe622;", // 对应字体图标的Unicode码
id: 'Root',
label: '可疑人员王**',
text: '\ue6b2', // 对应iconfont.css 里面的content注意加u后面的自行修改一下。
style: {
fill: "red"
fill: 'red',
},
labelCfg: {
style: {
fill: "red"
}
fill: 'red',
},
},
backgroundConfig: null, // 自定义项,用于判读是否需要圆背景
size: 30,
children: [
{
id: "SubTreeNode1",
label: "**网咖",
text: "&#xe605;",
relation: "上网",
id: 'SubTreeNode1',
label: '**网咖',
text: '&#xe605;',
relation: '上网',
children: [
{
id: "SubTreeNode2",
label: "多伦多",
text: "&#xe64b;"
id: 'SubTreeNode2',
label: '多伦多',
text: '&#xe64b;',
},
{
id: "id1",
label: "小王",
text: "&#xe622;",
id: 'id1',
label: '小王',
text: '&#xe622;',
children: [
{
id: "SubTreeNode1.2.1",
label: "182****2123",
text: "&#xe60d;"
id: 'SubTreeNode1.2.1',
label: '182****2123',
text: '&#xe60d;',
},
{
id: "SubTreeNode4",
label: "今晚在吗",
text: "&#xe629;"
}
]
}
]
id: 'SubTreeNode4',
label: '今晚在吗',
text: '&#xe629;',
},
],
},
],
},
{
id: "SubTreeNode3",
label: "subway",
text: "&#xe653;",
id: 'SubTreeNode3',
label: 'subway',
text: '&#xe653;',
children: [
{
id: "SubTreeNode3.1",
label: "王五",
text: "&#xe622;"
id: 'SubTreeNode3.1',
label: '王五',
text: '&#xe622;',
},
{
id: "SubTreeNode3.2",
label: "张三",
text: "&#xe622;"
}
]
id: 'SubTreeNode3.2',
label: '张三',
text: '&#xe622;',
},
],
},
{
id: "SubTreeNode5",
label: "小花",
relation: "老婆",
text: "&#xe74b;",
id: 'SubTreeNode5',
label: '小花',
relation: '老婆',
text: '&#xe74b;',
backgroundConfig: {
fill: "Coral"
fill: 'Coral',
},
style: {
fill: "#fff"
fill: '#fff',
},
labelCfg: {
style: {
fill: "Coral"
}
fill: 'Coral',
},
},
children: [
{
id: "SubTreeNode1.2.1",
label: "182****2123",
text: "&#xe60d;",
relation: "通话",
id: 'SubTreeNode1.2.1',
label: '182****2123',
text: '&#xe60d;',
relation: '通话',
backgroundConfig: {
fill: "Coral"
fill: 'Coral',
},
style: {
fill: "#fff"
fill: '#fff',
},
labelCfg: {
style: {
fill: "Coral"
}
}
fill: 'Coral',
},
},
},
{
id: "SubTreeNode3.3",
label: "凶器",
text: "&#xe673;",
relation: "指纹",
id: 'SubTreeNode3.3',
label: '凶器',
text: '&#xe673;',
relation: '指纹',
backgroundConfig: {
fill: "Coral"
fill: 'Coral',
},
style: {
fill: "#fff"
fill: '#fff',
},
labelCfg: {
style: {
fill: "Coral"
}
}
}
]
fill: 'Coral',
},
},
},
],
},
{
id: "SubTreeNode6",
label: "马航37*",
relation: "乘坐",
text: "&#xe610;"
}
]
id: 'SubTreeNode6',
label: '马航37*',
relation: '乘坐',
text: '&#xe610;',
},
],
};
graph.data(data);
graph.render();
```
## 注意事项
看了代码大家应该很清楚了,实质就是用了 text 图形,但有几个需要注意的地方:<br />**1、text的fontFamily必须和iconfont.css里面的font-family保持一致**<br />
## Attention
In fact, iconfont is a text shape.
<br />**1、The `fontFamily` of the text and the `font-family` in iconfont.css shoulde be kept consistent:**<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*v0CoQoNIyJ8AAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*wndRQo6U-oUAAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
**2、data 里面的 text 使用的是 Unicode需要自行复制。**<br />
**2、The `text` in data is the `content` in iconfont.css. And add an `u` after `\`.**<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*SV8TRrKFLD8AAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*KO-IRbIXRGAAAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*NF3mQYRurWsAAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*teUAQIkCffUAAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
## Tool Function getIcon
You can write a function as below to transform unicode. Attention, unicode cannot be connected manually (`\\u${icon.unicode}`). Here we use the `code_decimal` in iconfont.json. For more detail, please refer to [MDN String.fromCodePoint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint).
```javascript
import fonts from '../fonts/iconfont.json';
const icons = fonts.glyphs.map(icon => {
return {
name: icon.name,
unicode: String.fromCodePoint(icon.unicode_decimal), // `\\u${icon.unicode}`,
};
});
const getIcon = (type: string) => {
const matchIcon = icons.find(icon => {
return icon.name === type;
}) || { unicode: '', name: 'default' };
return matchIcon.unicode;
};
```
### Usage
```javascript
{
shape: 'text',
attrs: {
id: 'node-icon',
x: 0,
y: 0,
fontSize: iconSize,
fill: primaryColor,
text: getIcon('logo'), //logo is the name of the unicode
fontFamily: 'iconfont', // same as font-family: "iconfont"; in CSS
textAlign: 'center',
textBaseline: 'middle',
},
}
```

View File

@ -4,23 +4,23 @@ order: 9
---
## 简介
为什么使用 iconfont 兼容性好、种类多、多色等。在此不做过多介绍请直接移步[阿里巴巴-iconfont平台](https://www.iconfont.cn)
为什么使用 iconfont 兼容性好、种类多、多色等。在此不做过多介绍请直接移步 <a href='https://www.iconfont.cn' target='_blank'>阿里巴巴-iconfont平台</a>
## 效果
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*rJ3lQa0HR-wAAAAAAAAAAABkARQnAQ' alt='result' width='450'/>
## 下载字体图标
直接去到[阿里巴巴字体图标库](https://www.iconfont.cn)搜索下载即可,简要操作流程是:搜索图标(例如篮球) ->  选择自己喜欢的图标添加入库  ->  点击页面右上角的购物车可以看到我们加入的图标 -> 添加至项目,如果没有项目到话可以新建一个  ->  在我到项目里面点击下载至本地 -> 解压。如果一切操作正常的话可以得到如下解压文件:<br />
直接<a href='https://www.iconfont.cn' target='_blank'>阿里巴巴字体图标库</a> 搜索下载即可,简要操作流程是:搜索图标(例如篮球)-> 选择自己喜欢的图标添加入库 -> 点击页面右上角的购物车可以看到我们加入的图标 -> 添加至项目,如果没有项目到话可以新建一个 -> 在我到项目里面点击下载至本地 -> 解压。如果一切操作正常的话可以得到如下解压文件:<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*EnNmQ5m7xHUAAAAAAAAAAABkARQnAQ' alt='download' width='550'/>
选中红色区域的所有文件(这里面很多文件是不需要的,为了方便起见,我们全部复制即可,不需要的也不会被打包),复制到项目里面,一般放在目录 'static/icons' 或者 'assets/icons' 下面,如果没有的话可以新建目录,当然你也可以放到任意你喜欢的位置,只要引入的时候路径对即可,到此 iconfont 引入完毕。
PS: 本案文件目录为 '/static/icons'
PS: 本案文件目录为 '/static/icons'
## 引入G6
## 引入 G6
多种引入方式,请移步[快速上手](/zh/docs/manual/getting-started)。
<br />PS: 本案例简单粗暴通过CDN的方式引入。
<br />PS: 本案例简单粗暴,通过 CDN 的方式引入。
```html
<script src="https://gw.alipayobjects.com/os/antv/pkg/_antv.g6-3.2.0/build/g6.js"></script>
@ -37,82 +37,78 @@ PS: 本案文件目录为 '/static/icons'
## 使用字体
```javascript
G6.registerNode("iconfont", {
G6.registerNode('iconfont', {
draw(cfg, group) {
const {
backgroundConfig: backgroundStyle,
style,
labelCfg: labelStyle
} = cfg;
const { backgroundConfig: backgroundStyle, style, labelCfg: labelStyle } = cfg;
if (backgroundStyle) {
group.addShape("circle", {
group.addShape('circle', {
attrs: {
x: 0,
y: 0,
r: cfg.size,
...backgroundStyle
}
...backgroundStyle,
},
});
}
const keyShape = group.addShape("text", {
const keyShape = group.addShape('text', {
attrs: {
x: 0,
y: 0,
fontFamily: "iconfont", // 对应css里面的font-family: "iconfont";
textAlign: "center",
textBaseline: "middle",
fontFamily: 'iconfont', // 对应css里面的font-family: "iconfont";
textAlign: 'center',
textBaseline: 'middle',
text: cfg.text,
fontSize: cfg.size,
...style
}
...style,
},
});
const labelY = backgroundStyle ? cfg.size * 2 : cfg.size;
group.addShape("text", {
group.addShape('text', {
attrs: {
x: 0,
y: labelY,
textAlign: "center",
textAlign: 'center',
text: cfg.label,
...labelStyle.style
}
...labelStyle.style,
},
});
return keyShape;
}
},
});
const COLOR = "#40a9ff";
const COLOR = '#40a9ff';
const graph = new G6.TreeGraph({
container: "mountNode",
container: 'mountNode',
width: 800,
height: 600,
modes: {
default: ["collapse-expand", "drag-canvas", "drag-node"]
default: ['collapse-expand', 'drag-canvas', 'drag-node'],
},
defaultNode: {
backgroundConfig: {
backgroundType: "circle",
backgroundType: 'circle',
fill: COLOR,
stroke: "LightSkyBlue"
stroke: 'LightSkyBlue',
},
shape: "iconfont",
shape: 'iconfont',
size: 12,
style: {
fill: "#fff"
fill: '#fff',
},
labelCfg: {
style: {
fill: COLOR,
fontSize: 12
}
}
fontSize: 12,
},
},
},
// 布局相关
layout: {
type: "compactBox",
direction: "LR",
type: 'compactBox',
direction: 'LR',
getId(d) {
return d.id;
},
@ -127,150 +123,148 @@ const graph = new G6.TreeGraph({
},
getHGap() {
return 60;
}
}
},
},
});
graph.edge(({ target }) => {
const fill =
target.get("model").backgroundConfig &&
target.get("model").backgroundConfig.fill;
const fill = target.get('model').backgroundConfig && target.get('model').backgroundConfig.fill;
return {
shape: "cubic-horizontal",
shape: 'cubic-horizontal',
color: fill || COLOR,
label: target.get("model").relation || "",
label: target.get('model').relation || '',
labelCfg: {
style: {
fill: fill || COLOR,
fontSize: 12
}
}
fontSize: 12,
},
},
};
});
const data = {
isRoot: true,
id: "Root",
label: "可疑人员王**",
text: "&#xe622;", // 对应字体图标的Unicode码
id: 'Root',
label: '可疑人员王**',
text: '\ue6b2', // 对应iconfont.css 里面的content注意加u后面的自行修改一下。
style: {
fill: "red"
fill: 'red',
},
labelCfg: {
style: {
fill: "red"
}
fill: 'red',
},
},
backgroundConfig: null, // 自定义项,用于判读是否需要圆背景
size: 30,
children: [
{
id: "SubTreeNode1",
label: "**网咖",
text: "&#xe605;",
relation: "上网",
id: 'SubTreeNode1',
label: '**网咖',
text: '&#xe605;',
relation: '上网',
children: [
{
id: "SubTreeNode2",
label: "多伦多",
text: "&#xe64b;"
id: 'SubTreeNode2',
label: '多伦多',
text: '&#xe64b;',
},
{
id: "id1",
label: "小王",
text: "&#xe622;",
id: 'id1',
label: '小王',
text: '&#xe622;',
children: [
{
id: "SubTreeNode1.2.1",
label: "182****2123",
text: "&#xe60d;"
id: 'SubTreeNode1.2.1',
label: '182****2123',
text: '&#xe60d;',
},
{
id: "SubTreeNode4",
label: "今晚在吗",
text: "&#xe629;"
}
]
}
]
id: 'SubTreeNode4',
label: '今晚在吗',
text: '&#xe629;',
},
],
},
],
},
{
id: "SubTreeNode3",
label: "subway",
text: "&#xe653;",
id: 'SubTreeNode3',
label: 'subway',
text: '&#xe653;',
children: [
{
id: "SubTreeNode3.1",
label: "王五",
text: "&#xe622;"
id: 'SubTreeNode3.1',
label: '王五',
text: '&#xe622;',
},
{
id: "SubTreeNode3.2",
label: "张三",
text: "&#xe622;"
}
]
id: 'SubTreeNode3.2',
label: '张三',
text: '&#xe622;',
},
],
},
{
id: "SubTreeNode5",
label: "小花",
relation: "老婆",
text: "&#xe74b;",
id: 'SubTreeNode5',
label: '小花',
relation: '老婆',
text: '&#xe74b;',
backgroundConfig: {
fill: "Coral"
fill: 'Coral',
},
style: {
fill: "#fff"
fill: '#fff',
},
labelCfg: {
style: {
fill: "Coral"
}
fill: 'Coral',
},
},
children: [
{
id: "SubTreeNode1.2.1",
label: "182****2123",
text: "&#xe60d;",
relation: "通话",
id: 'SubTreeNode1.2.1',
label: '182****2123',
text: '&#xe60d;',
relation: '通话',
backgroundConfig: {
fill: "Coral"
fill: 'Coral',
},
style: {
fill: "#fff"
fill: '#fff',
},
labelCfg: {
style: {
fill: "Coral"
}
}
fill: 'Coral',
},
},
},
{
id: "SubTreeNode3.3",
label: "凶器",
text: "&#xe673;",
relation: "指纹",
id: 'SubTreeNode3.3',
label: '凶器',
text: '&#xe673;',
relation: '指纹',
backgroundConfig: {
fill: "Coral"
fill: 'Coral',
},
style: {
fill: "#fff"
fill: '#fff',
},
labelCfg: {
style: {
fill: "Coral"
}
}
}
]
fill: 'Coral',
},
},
},
],
},
{
id: "SubTreeNode6",
label: "马航37*",
relation: "乘坐",
text: "&#xe610;"
}
]
id: 'SubTreeNode6',
label: '马航37*',
relation: '乘坐',
text: '&#xe610;',
},
],
};
graph.data(data);
@ -278,15 +272,55 @@ graph.render();
```
## 注意事项
看了代码大家应该很清楚了,实质就是用了 text 图形,但有几个需要注意的地方:<br />**1、text的fontFamily必须和iconfont.css里面的font-family保持一致**<br />
看了代码大家应该很清楚了,实质就是用了 text 图形,但有几个需要注意的地方:<br />**1、text `fontFamily` 必须和 iconfont.css 里面的 `font-family` 保持一致:**<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*v0CoQoNIyJ8AAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*wndRQo6U-oUAAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
**2、data 里面的 text 使用的是 Unicode需要自行复制。**<br />
**2、data 里面的 `text` 使用的是 iconfont.css 里面的 `content`,注意加 `u` 。如有需要可自行复制。**<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*SV8TRrKFLD8AAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*KO-IRbIXRGAAAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*NF3mQYRurWsAAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*teUAQIkCffUAAAAAAAAAAABkARQnAQ' alt='download' width='600'/>
## 工具函数 getIcon
我们可以将 unicode 的转化封装成函数使用。这里注意,手动拼接 unicode 是不行的(`\\u${icon.unicode}`)。这里采用 iconfont.json 中的 `code_decimal` 进行转化。详细参考《[MDN String.fromCodePoint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)》。
```javascript
import fonts from '../fonts/iconfont.json';
const icons = fonts.glyphs.map(icon => {
return {
name: icon.name,
unicode: String.fromCodePoint(icon.unicode_decimal), // `\\u${icon.unicode}`,
};
});
const getIcon = (type: string) => {
const matchIcon = icons.find(icon => {
return icon.name === type;
}) || { unicode: '', name: 'default' };
return matchIcon.unicode;
};
```
### 用法
```javascript
{
shape: 'text',
attrs: {
id: 'node-icon',
x: 0,
y: 0,
fontSize: iconSize,
fill: primaryColor,
text: getIcon('logo'), // logo 为 unicode 对应的 name
fontFamily: 'iconfont', // 对应 CSS 里面的 font-family: "iconfont";
textAlign: 'center',
textBaseline: 'middle',
},
}
```

View File

@ -0,0 +1,68 @@
---
title: Graphics Group
order: 1
---
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;<strong>Attention:</strong> </span>
<br />Graphics Group and [Node Group](/en/docs/manual/middle/nodeGroup) are totally different concepts with the same name Group.
- Graphics Group is the group for [Graphics Shape](/en/docs/manual/middle/keyconcept/shape-keyshape);
- [Node Group](/en/docs/manual/middle/nodeGroup) is the group for [Node](/en/docs/manual/middle/elements/nodes/defaultNode)s, which is related to the hierarchy and groups in the data.
<br />
## What
Graphics Group (hereinafter referred to as Group) in G6 is similar to <a href='https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g' target='_blank'> `<g>` tag in SVG </a>: Group a container of a group of graphics. The transformations on a Group such as clipping, rotating, zooming, and translating will be applied to all the children of the Group. The properties like color and position will also be inherited by its children. Besides, Group can be nested for complicated objects.
In G6, all the nodes instances in a Graph is grouped by a Group named `nodeGroup`, all the edges instances are grouped by `edgeGroup`. And the visual level (zIndex) of `nodeGroup` is higher than `edgeGroup`, which means all the nodes will be drawed on the top of all the edges.
<br />As shown in the figure below: The three nodes in (Left) are belong to the `nodeGroup`, the two edges are belong to the `edgeGroup`. The visual level (zIndex) of `nodeGroup` is higher than `edgeGroup`, so the three nodes are drawed on the top of the two edges. We reduce the opacity of the nodes in (Right) to clearly see the edges are drawed under the nodes.<br />
![image.png](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*oqKUSoRWMrcAAAAAAAAAAABkARQnAQ)![image.png](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*cudnTqD-g_4AAAAAAAAAAABkARQnAQ)
> (Left) Demonstration of the graphics Group of nodes and edges. (Right) Nodes with opacity.
## When
Graphics Group is refered by [Custom Node](/en/docs/manual/advanced/custom-node) and [Custom Edge](/en/docs/manual/advanced/custom-edge). It is a mechanism to combine and manage the graphis shapes.
<br />For example, there is a node A which has a group contains all the graphics shapes (a circle and a text shape) of A. Node B is a custom node which also has a group contains all the graphics shapes (a circle, a rect, and a text shape) of B.<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GnVoSIGkXhsAAAAAAAAAAABkARQnAQ' alt='img' width='100'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*iQXZTZCX9LEAAAAAAAAAAABkARQnAQ' alt='img' width='100'/>
<br />
## How
The functions below will be used in [Custom Node](/en/docs/manual/advanced/custom-node) and [Custom Edge](/en/docs/manual/advanced/custom-edge).
### Instantiating a Group
```
const group = new Group(cfgs);
```
### Functions of Group
- addGroup(cfgs)
Add a new group to the group.
```javascript
const subGroup = group.addGroup({
id: 'rect'
})
```
- addShape(type, cfgs)
Add a shape to the group.
```javascript
const keyShape = group.addShape('rect', {
attrs: {
stroke: 'red'
}
})
```
**Tips:** The `clip`, `transform`, and other operations on a group will affect all the elements in the group.

View File

@ -1,27 +1,27 @@
---
title: 关键概念-图形分组 Group
title: 图形分组 Group
order: 1
---
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;注意:</span>
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;<strong>⚠️注意:</strong></span>
<br />图形分组 Group 与 [节点分组 Group](/zh/docs/manual/middle/nodeGroup) 虽然都名为 Group但属于不同层次的概念。
- 图形分组针对 [图形 Shape](/zh/docs/manual/middle/keyConcept) 层次的分组;
- [节点分组 Group](/zh/docs/manual/middle/nodeGroup) 是针对 [节点](/zh/docs/manual/middle/elements/defaultNode) 的分组,与数据结构中的层次、分组对应。
- 图形分组针对 [图形 Shape](/zh/docs/manual/middle/keyconcept/shape-keyshape) 层次的分组;
- [节点分组 Group](/zh/docs/manual/middle/nodeGroup) 是针对 [节点](/zh/docs/manual/middle/elements/nodes/defaultNode) 的分组,与数据结构中的层次、分组对应。
<br />
## 什么是图形分组 Group
图形分组 group 类似于 [SVG 中的 ](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g)[`<g>`](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g)[ 标签](https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g):元素 `g` 是用来组合图形对象的容器。在 group 上添加变换例如剪裁、旋转、放缩、平移等会应用到其所有的子元素上。在 group 上添加属性例如颜色、位置等会被其所有的子元素继承。此外 group 可以多层嵌套使用,因此可以用来定义复杂的对象。
图形分组 group 类似于 <a href='https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g' target='_blank'>SVG 中的 `<g>` 标签</a>:元素 `g` 是用来组合图形对象的容器。在 group 上添加变换例如剪裁、旋转、放缩、平移等会应用到其所有的子元素上。在 group 上添加属性例如颜色、位置等会被其所有的子元素继承。此外 group 可以多层嵌套使用,因此可以用来定义复杂的对象。
在 G6 中Graph 的一个实例中的所有节点属于同一个变量名为 `nodeGroup` 的 group所有的边属于同一个变量名为 `edgeGroup` 的 group。节点 group 在视觉上的层级zIndex高于边 group即所有节点会绘制在所有边的上层。<br />如下图(左)三个节点属于 `nodeGroup` ,两条边属于 `edgeGroup`  `nodeGroup` 层级高于 `edgeGroup` ,三个节点绘制在条边的上层。下图(右)是(左)图的节点降低透明度后的效果,可以更清晰看到边绘制在节点下方。<br />
在 G6 中Graph 的一个实例中的所有节点属于同一个变量名为 `nodeGroup` 的 group所有的边属于同一个变量名为 `edgeGroup` 的 group。节点 group 在视觉上的层级zIndex高于边 group即所有节点会绘制在所有边的上层。<br />如下图(左)三个节点属于 `nodeGroup` ,两条边属于 `edgeGroup`  `nodeGroup` 层级高于 `edgeGroup` ,三个节点绘制在条边的上层。下图(右)是(左)图的节点降低透明度后的效果,可以更清晰看到边绘制在节点下方。<br />
![image.png](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*oqKUSoRWMrcAAAAAAAAAAABkARQnAQ)![image.png](https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*cudnTqD-g_4AAAAAAAAAAABkARQnAQ)
> (左)节点和边的图形分组 Group 演示。(右)给左图的节点降低了透明度。
## 何时使用图形分组 Group
[自定义节点](https://www.yuque.com/antv/g6/self-node)、[自定义边](https://www.yuque.com/antv/g6/self-edge)时将会涉及到图形分组 Group 的概念。图形分组 Group 方便了用户对节点或边上元素的组合和管理。<br />例如,如下图中的节点 A 有一个包含节点 A 中所有图形的 group该 group 中包含了一个 circle 图形和一个文本图形。节点 B 是一个自定义节点,有一个包含节点 B 中所有图形的 group该 group 包含了 circle 图形、rect 图形、文本图形。<br />
[自定义节点](/zh/docs/manual/advanced/custom-node)、[自定义边](/zh/docs/manual/advanced/custom-edge)时将会涉及到图形分组 Group 的概念。图形分组 Group 方便了用户对节点或边上元素的组合和管理。<br />例如,如下图中的节点 A 有一个包含节点 A 中所有图形的 group该 group 中包含了一个 circle 图形和一个文本图形。节点 B 是一个自定义节点,有一个包含节点 B 中所有图形的 group该 group 包含了 circle 图形、rect 图形、文本图形。<br />
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*GnVoSIGkXhsAAAAAAAAAAABkARQnAQ' alt='img' width='100'/>
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*iQXZTZCX9LEAAAAAAAAAAABkARQnAQ' alt='img' width='100'/>
@ -61,4 +61,4 @@ const keyShape = group.addShape('rect', {
```
提示:在分组上添加的 `clip` `transform` 等会影响到该分组中的所有图形。
提示:在分组上添加的 `clip` `transform` 等会影响到该分组中的所有元素(子分组或图形

View File

@ -0,0 +1,293 @@
---
title: Graphics Shape Properties
order: 0
---
An item (node/edge) in G6 **Consists of One or More** [**Graphics Shape**](/en/docs/manual/middle/keyconcept/shape-keyshape). You can add shapes to a custom item by `group.addShape` in the `draw` function of registering item. The shapes in G6:
- [circle](#circle);
- [rect](#rect);
- [ellipse](#ellipse);
- [polygon](#polygon);
- [fan](#fan);
- [image](#image);
- [marker](#marker);
- [path](#path);
- [text](#text).
## The Common Properties of Shapes
| Name | Description | Remark |
| --- | --- | --- |
| fill | The color, gradient color, or the pattern for filling | Corresponds to the `fillStyle` of Canvas |
| stroke | The color, gradient color, or pattern for the stroke | Corresponds to the `strokeStyle` of Canvas |
| shadowColor | The color for shadow | |
| shadowBlur | The blur level for shadow | Larger the value, more blur |
| shadowOffsetX | The horizontal offset of the shadow | |
| shadowOffsetY | The vertical offset of the shadow | |
| opacity | The opacity (alpha value) of the shape | Corresponds to the `globalAlpha` of Canvas |
### Usage
```javascript
group.addShape('rect', {
attrs: {
fill: 'red',
shadowOffsetX: 10,
shadowOffsetY: 10,
shadowColor: 'blue',
shadowBlur: 10,
opacity: 0.8
}
})
```
## Circle
### Property
| Name | Description |
| --- | --- |
| x | The x coordinate of the center |
| y | The y coordinate of the center |
| r | The radius |
### Usage
```javascript
group.addShape('circle', {
attrs: {
x: 100,
y: 100,
r: 50,
fill: 'blue'
}
})
```
## Rect
### Property
| Name | Description | Remark |
| --- | --- | --- |
| x | The x coordinate of the left top | |
| y | The y coordinate of the left top | |
| width | The width of the rect | |
| height | The height of the rect | |
| radius | The border radius. | It can be an integer or an array, representing the border radii of lefttop, righttop, rightbottom, leftbotton respectively. <br />- `radius: 1` or `radius: [ 1 ]` is equal to `radius: [ 1, 1, 1, 1 ]`<br />- `radius: [ 1, 2 ]` is equal to `radius: [ 1, 2, 1, 2 ]`<br />- `radius: [ 1, 2, 3 ]` is equal to `radius: [ 1, 2, 3, 2 ]`<br /> |
### Usage
```javascript
group.addShape('rect', {
attrs: {
x: 150,
y: 150,
width: 150,
height: 150,
stroke: 'black',
radius: [2, 4]
}
});
```
## Ellipse
### Property
| Name | Description |
| --- | --- |
| x | The x coordinate of the center |
| y | The y coordinate of the center |
| rx | The horizontal radius of the ellipse |
| ry | The vertical radius of the ellipse |
### Usage
```javascript
group.addShape('ellipse', {
attrs: {
x: 100,
y: 100,
rx: 50,
ry: 50,
fill: 'blue'
}
})
```
## Polygon
### Property
| Name | Description | Remark |
| --- | --- | --- |
| points | A set of vertexes' coordinates of the polygon | It is an array |
### Usage
```javascript
group.addShape('polygon', {
attrs: {
points:[[ 30, 30 ], [ 40, 20 ], [ 30, 50 ], [ 60, 100 ]],
fill: 'red'
}
});
```
## Fan
### Property
| Name | Description | Remark |
| --- | --- | --- |
| x | The x coordinate of the center | |
| y | The y coordinate of the center | |
| rs | The horizontal radius of the fan | |
| re | The vertical radius of the fan | |
| startAngle | The start angle | Radian system represented by Math.PI |
| endAngle | The end angle | Radian system represented by Math.PI |
| clockwise | It will be rendered clockwisely if it is `true`, counterclockwisely if it is `false` | |
### Usage
```javascript
group.addShape('fan', {
attrs: {
x: 50,
y: 50,
re: 40,
rs: 30,
startAngle: 1/2 * Math.PI,
endAngle: Math.PI,
clockwise: false,
fill: '#b7eb8f'
}
})
```
## Image
### Property
| Name | Description | Remark |
| --- | --- | --- |
| x | The x coordinate of the left top of the image | |
| y | The y coordinate of the left top of the image | |
| width | The width of the image | |
| height | The height of the image | |
| img | The source of the image | Supports: url, ImageData, Image, and canvas |
### Usage
```javascript
group.addShape('image', {
attrs: {
x: 0,
y: 0,
img:'https://g.alicdn.com/cm-design/arms-trace/1.0.155/styles/armsTrace/images/TAIR.png'
}
})
```
## Marker
### Property
| Name | Description | Remark |
| --- | --- | --- |
| x | The x coordinate of the center | |
| y | The y coordinate of the center | |
| r | The radius of the marker | |
| symbol | The shape | We built in some commonly used shapes for it: `circle`, `square`, `diamond`, `triangle`, and `triangle-down`. You can customize it by path |
### Usage
```javascript
group.addShape('marker', {
attrs: {
x: 10,
y: 10,
r: 10,
symbol: function(x, y, r) {
return [
[ 'M', x, y ],
[ 'L', x + r, y + r ],
[ 'L', x + r * 2, y ],
[ 'Z' ]
]
}
}
});
```
## Path
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;<strong>Attention:</strong> </span>
When the edge is too thin to be hitted by mouse, set **lineAppendWidth** to enlarge the hitting area.
### Property
| Name | Description | Remark |
| --- | --- | --- |
| path | The path. | It can be a String, or an Array of path |
| startArrow | The arrow on the start of the path | When `startArrow` is `true`, show a default arrow on the start of the path. User can customize an arrow by path |
| endArrow | The arrow on the end of the path | When `startArrow` is `true`, show a default arrow on the end of the path. User can customize an arrow by path |
| lineAppendWidth | The hitting area of the path | Enlarge the hitting area by enlarging its value |
| lineCap | The style of two ends of the path | |
| lineJoin | The style of the intersection of two path | |
| lineWidth | The line width of the current path | |
| miterLimit | The maximum miter length | |
| lineDash | The style of the dash line | It is an array that describes the length of gaps and line segments. If the number of the elements in the array is odd, the elements will be dulplicated. Such as [5, 15, 25] will be regarded as [5, 15, 25, 5, 15, 25] |
### Usage
```javascript
group.addShape('path', {
attrs: {
startArrow: {
path: 'M 10,0 L -10,-10 L -10,10 Z', // The custom arrow is a path centered at (0, 0), and points to the positive direction of x-axis
d: 10
},
endArrow: {
path: 'M 10,0 L -10,-10 L -10,10 Z', // The custom arrow is a path centered at (0, 0), and points to the positive direction of x-axis
d: 10
},
path: [
[ 'M', 100, 100 ],
[ 'L', 200, 200 ]
],
stroke: '#000',
lineWidth: 8,
lineAppendWidth: 5
}
});
```
## Text
### Properties
| Name | Description | Remark |
| --- | --- | --- |
| fill | The color or gradient color for filling. | The corresponding property in Canvas is `fillStyle`. |
| stroke | The color, gradient color, or pattern for stroke. | The corresponding property in Canvas is `strokeStyle`. |
| shadowColor | The color for shadow. | |
| shadowBlur | The blur level for shadow. | Larger the value, more blur. |
| shadowOffsetX | The horizontal offset of the shadow. | |
| shadowOffsetY | The vertical offset of the shadow. | |
| opacity | The opacity (alpha value) of the shape. | The corresponding property in Canvas is `globalAlpha`. |
| font | The font of the text. | |
| textAlign | The align way of the text. | Options: `'center'` / `'end'` / `'left'` / `'right'` / `'start'`. `'start'` by default. |
| textBaseline | The base line of the text. | Options: <br />`'top'` / `'middle'` / `'bottom'` / `'alphabetic'` / `'hanging'`. `'bottom'` by default. |
| fontStyle | The font style of the text. | The corresponding property in CSS is `font-style` |
| fontVariant | The font variant of the text. | The corresponding property in CSS is `font-variant` |
| fontWeight | The font weight of the text. | The corresponding property in CSS is `font-weight` |
| fontSize | The font size of the text. | The corresponding property in CSS is `font-size` |
| fontFamily | The font family of the text. | The corresponding property in CSS is `font-family` |
| autoRotate | Wheter rotate the text according to the edge automatically if it is a label of an edge. | |
### Usage
```javascript
group.addShape('text', {
attrs: {
text: 'test text',
fill: 'red',
fontWeight: 400,
shadowOffsetX: 10,
shadowOffsetY: 10,
shadowColor: 'blue',
shadowBlur: 10
}
});
```

View File

@ -1,32 +1,31 @@
---
title: 关键概念-图形 Shape 及其属性
title: 图形 Shape 及其属性
order: 0
---
G6 中的元素(节点/边)是**由一个或多个小**[**图形 Shape**](https://www.yuque.com/antv/g6/shape-crycle)**组成**,主要通过自定义节点或自定义边时在 `draw` 方法中使用 `group.addShape` 添加G6 中支持以下的图形 Shape
G6 中的元素(节点/边)是**由一个或多个**[**图形 Shape**](/zh/docs/manual/middle/keyconcept/shape-keyshape)**组成**,主要通过自定义节点或自定义边时在 `draw` 方法中使用 `group.addShape` 添加G6 中支持以下的图形 Shape
- circle
- rect矩形
- ellipse椭圆
- image图片
- text文本的属性请参考[这里](https://www.yuque.com/antv/g6/gs4gno)
- fan扇形
- marker标记
- polygon多边形
- path路径。
- [circle](#圆图形-circle):圆;
- [rect](#矩形图形-rect):矩形;
- [ellipse](#椭圆图形-ellipse):椭圆;
- [polygon](#多边形图形-polygon):多边形
- [fan](#扇形图形-fan):扇形
- [image](#图片图形-image):图片
- [marker](#标记图形-marker):标记;
- [path](#路径-path):路径。
- [text](#文本-text):文本;
## 各图形 Shape 的通用属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| fill | 设置用于填充绘画的颜色、渐变或模式 | 对应 canvas 属性 `fillStyle` |
| stroke | 设置用于笔触的颜色、渐变或模式 | 对应 canvas 属性 `strokeStyle` |
| fill | 设置用于填充绘画的颜色、渐变或模式 | 对应 Canvas 属性 `fillStyle` |
| stroke | 设置用于笔触的颜色、渐变或模式 | 对应 Canvas 属性 `strokeStyle` |
| shadowColor | 设置用于阴影的颜色 | |
| shadowBlur | 设置用于阴影的模糊级别 | 数值越大,越模糊 |
| shadowOffsetX | 设置阴影距形状的水平距离 | |
| shadowOffsetY | 设置阴影距形状的垂直距离 | |
| opacity | 设置绘图的当前 alpha 或透明值 | 对应 canvas 属性 `globalAlpha` |
| opacity | 设置绘图的当前 alpha 或透明值 | 对应 Canvas 属性 `globalAlpha` |
### 用法
```javascript
@ -44,11 +43,11 @@ group.addShape('rect', {
## 圆图形 Circle
### 属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| x | 圆心的 x 坐标 | |
| y | 圆心的 y 坐标 | |
| r | 圆的半径 | |
| 属性名 | 含义 |
| --- | --- |
| x | 圆心的 x 坐标 |
| y | 圆心的 y 坐标 |
| r | 圆的半径 |
### 用法
@ -63,14 +62,41 @@ group.addShape('circle', {
})
```
## 椭圆图形 Ellipse
## 矩形图形 Rect
### 属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| x | 圆心的 x 坐标 | |
| y | 圆心的 y 坐标 | |
| rx | 水平半径 | |
| ry | 垂直半径 | |
| x | 矩形左上角的 x 坐标 | |
| y | 矩形左上角的 y 坐标 | |
| width | 矩形的宽度 | |
| height | 矩形的高度 | |
| radius | 定义圆角 | 支持整数或数组形式, 分别对应左上、右上、右下、左下角的半径:<br />- radius 缩写为 1 或 [ 1 ] 相当于 [ 1, 1, 1, 1 ]<br />- radius 缩写为 [ 1, 2 ] 相当于 [ 1, 2, 1, 2 ]<br />- radius 缩写为 [ 1, 2, 3 ] 相当于 [ 1, 2, 3, 2 ]<br /> |
### 用法
```javascript
group.addShape('rect', {
attrs: {
x: 150,
y: 150,
width: 150,
height: 150,
stroke: 'black',
radius: [2, 4]
}
});
```
## 椭圆图形 Ellipse
### 属性
| 属性名 | 含义 |
| --- | --- |
| x | 圆心的 x 坐标 |
| y | 圆心的 y 坐标 |
| rx | 水平半径 |
| ry | 垂直半径 |
### 用法
@ -86,6 +112,23 @@ group.addShape('ellipse', {
})
```
## 多边形图形 Polygon
### 属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| points | 多边形的所有端点坐标 | 数组形式 |
### 用法
```javascript
group.addShape('polygon', {
attrs: {
points:[[ 30, 30 ], [ 40, 20 ], [ 30, 50 ], [ 60, 100 ]],
fill: 'red'
}
});
```
## 扇形图形 Fan
### 属性
| 属性名 | 含义 | 备注 |
@ -94,8 +137,8 @@ group.addShape('ellipse', {
| y | 扇形圆心的 y 坐标 | |
| rs | 水平半径 | |
| re | 垂直半径 | |
| startAngle | 起点弧度 | 弧度是弧度,即使用 Math.PI 表示 |
| endAngle | 终点弧度 | |
| startAngle | 起点弧度 | 弧度,即使用 Math.PI 表示 |
| endAngle | 终点弧度 | 弧度制,即使用 Math.PI 表示 |
| clockwise | 为 `true` 时顺时针渲染,为 `false` 时逆时针渲染 | |
@ -166,57 +209,15 @@ group.addShape('marker', {
});
```
## 多边形图形 Polygon
### 属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| points | 多边形的所有端点坐标 | 数组形式 |
### 用法
```javascript
group.addShape('polygon', {
attrs: {
points:[[ 30, 30 ], [ 40, 20 ], [ 30, 50 ], [ 60, 100 ]],
fill: 'red'
}
});
```
## 矩形图形 Rect
### 属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| x | 矩形左上角的 x 坐标 | |
| y | 矩形左上角的 y 坐标 | |
| width | 矩形的宽度 | |
| height | 矩形的高度 | |
| radius | 定义圆角 | 支持整数或数组形式, 分别对应左上、右上、右下、左下角的半径:<br />- radius 缩写为 1 或 [ 1 ] 相当于 [ 1, 1, 1, 1 ]<br />- radius 缩写为 [ 1, 2 ] 相当于 [ 1, 2, 1, 2 ]<br />- radius 缩写为 [ 1, 2, 3 ] 相当于 [ 1, 2, 3, 2 ]<br /> |
### 用法
```javascript
group.addShape('rect', {
attrs: {
x: 150,
y: 150,
width: 150,
height: 150,
stroke: 'black',
radius: [2, 4]
}
});
```
## 路径 Path
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;注意:</span>
<span style="background-color: rgb(251, 233, 231); color: rgb(139, 53, 56)"> &nbsp;&nbsp;<strong>⚠️注意:</strong></span>
边太细时候点击不中,请设置 `lineAppendWidth` 属性值。
### 属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| path | 线条路径 | 可以是 String 形式,也可以是线段的数组。 |
| startArrow | 起始端的箭头 | 为 `true`为默认的箭头效果,也可以是一个自定义箭头 |
| endArrow | 末尾端的箭头 | 为 `true`为默认的箭头效果,也可以是一个自定义箭头 |
| startArrow | 起始端的箭头 | 为 `true` 时在边的结束端绘制默认箭头,为 `false` 时不绘制结束端箭头。也可以是一个通过 path 自定义的箭头 |
| endArrow | 末尾端的箭头 | 为 `true` 时在边的开始端绘制默认箭头,为 `false` 时不绘制开始端箭头。也可以是一个通过 path 自定义的箭头 |
| lineAppendWidth | 边的击中范围 | 提升边的击中范围,扩展响应范围,数值越大,响应范围越广 |
| lineCap | 设置线条的结束端点样式 | |
| lineJoin | 设置两条线相交时,所创建的拐角形状 | |
@ -230,11 +231,11 @@ group.addShape('rect', {
group.addShape('path', {
attrs: {
startArrow: {
path: 'M 10,0 L -10,-10 L -10,10 Z', // 自定义箭头为中心点在(0, 0),指向 x 轴正方向的path
path: 'M 10,0 L -10,-10 L -10,10 Z', // 自定义箭头为中心点在(0, 0),指向 x 轴正方向的 path
d: 10
},
endArrow: {
path: 'M 10,0 L -10,-10 L -10,10 Z', // 自定义箭头为中心点在(0, 0),指向 x 轴正方向的path
path: 'M 10,0 L -10,-10 L -10,10 Z', // 自定义箭头为中心点在(0, 0),指向 x 轴正方向的 path
d: 10
},
path: [
@ -248,5 +249,42 @@ group.addShape('path', {
});
```
## 文本 Text
### 属性
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| fill | 设置用于填充绘画的颜色、渐变或模式 | 对应 Canvas 属性 `fillStyle` |
| stroke | 设置用于笔触的颜色、渐变或模式 | 对应 Canvas 属性 `strokeStyle` |
| shadowColor | 设置用于阴影的颜色 | |
| shadowBlur | 设置用于阴影的模糊级别 | 数值越大,越模糊 |
| shadowOffsetX | 设置阴影距形状的水平距离 | |
| shadowOffsetY | 设置阴影距形状的垂直距离 | |
| opacity | 设置绘图的当前 alpha 或透明值 | 对应 Canvas 属性 `globalAlpha` |
| font | 设置文本内容的当前字体属性 | |
| textAlign | 设置文本内容的当前对齐方式 | 支持的属性:`center` / `end` / `left` / `right` / `start`,默认值为 `start` |
| textBaseline | 设置在绘制文本时使用的当前文本基线 | 支持的属性:<br />`top` / `middle` / `bottom` / `alphabetic` / `hanging`。默认值为 `bottom` |
| fontStyle | 字体样式 | 对应 `font-style` |
| fontVariant | 设置为小型大写字母字体 | 对应 `font-variant` |
| fontWeight | 字体粗细 | 对应 `font-weight` |
| fontSize | 字体大小 | 对应 `font-size` |
| fontFamily | 字体系列 | 对应 `font-family` |
### 用法
```javascript
group.addShape('text', {
attrs: {
text: 'test text',
x: 0,
y: 10,
fontSize: 14,
textAlign: 'left',
textBaseline: 'middle',
fill: '#0000D9'
}
});
```

View File

@ -1,69 +0,0 @@
---
title: 文本属性
order: 4
---
## 属性
文本有以下可用的属性。
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| fill | 设置用于填充绘画的颜色、渐变或模式 | 对应 canvas 属性 `fillStyle` |
| stroke | 设置用于笔触的颜色、渐变或模式 | 对应 canvas 属性 `strokeStyle` |
| shadowColor | 设置用于阴影的颜色 | |
| shadowBlur | 设置用于阴影的模糊级别 | 数值越大,越模糊 |
| shadowOffsetX | 设置阴影距形状的水平距离 | |
| shadowOffsetY | 设置阴影距形状的垂直距离 | |
| opacity | 设置绘图的当前 alpha 或透明值 | 对应 canvas 属性 `globalAlpha` |
| font | 设置文本内容的当前字体属性 | |
| textAlign | 设置文本内容的当前对齐方式 | 支持的属性:`center`|`end`|`left`|`right`|`start`,默认值为`start` |
| textBaseline | 设置在绘制文本时使用的当前文本基线 | 支持的属性:<br />`top`|`middle`|`bottom` |`alphabetic`|`hanging`。默认值为 `bottom` |
| fontStyle | 字体样式 | 对应 font-style |
| fontVariant | 设置为小型大写字母字体 | 对应 font-variant |
| fontWeight | 字体粗细 | 对应 font-weight |
| fontSize | 字体大小 | 对应 font-size |
| fontFamily | 字体系列 | 对应 font-family |
| autoRotate | 是否自动旋转 | |
## 案例
```javascript
const data = {
nodes: [
{
id: 'node1',
x: 100,
y: 100,
shape: 'rect',
label: 'rect'
}
]
}
const graph = new G6.Graph({
container: 'mountNode',
width: 500,
height: 500
});
graph.data(data);
graph.render();
const node = graph.findById('node1')
graph.update(node, {
style: {
stroke: 'blue'
},
labelCfg: {
style: {
fill: 'red',
shadowOffsetX: 10,
shadowOffsetY: 10,
shadowColor: 'blue',
shadowBlur: 10
}
}
})
```
通过以上代码修改node中文本的样式效果如下图
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*0xkLS5shGJUAAAAAAAAAAABkARQnAQ' alt='download' width='150'/>

View File

@ -1,69 +0,0 @@
---
title: 文本属性
order: 4
---
## 属性
文本有以下可用的属性。
| 属性名 | 含义 | 备注 |
| --- | --- | --- |
| fill | 设置用于填充绘画的颜色、渐变或模式 | 对应 canvas 属性 `fillStyle` |
| stroke | 设置用于笔触的颜色、渐变或模式 | 对应 canvas 属性 `strokeStyle` |
| shadowColor | 设置用于阴影的颜色 | |
| shadowBlur | 设置用于阴影的模糊级别 | 数值越大,越模糊 |
| shadowOffsetX | 设置阴影距形状的水平距离 | |
| shadowOffsetY | 设置阴影距形状的垂直距离 | |
| opacity | 设置绘图的当前 alpha 或透明值 | 对应 canvas 属性 `globalAlpha` |
| font | 设置文本内容的当前字体属性 | |
| textAlign | 设置文本内容的当前对齐方式 | 支持的属性:`center`|`end`|`left`|`right`|`start`,默认值为`start` |
| textBaseline | 设置在绘制文本时使用的当前文本基线 | 支持的属性:<br />`top`|`middle`|`bottom` |`alphabetic`|`hanging`。默认值为 `bottom` |
| fontStyle | 字体样式 | 对应 font-style |
| fontVariant | 设置为小型大写字母字体 | 对应 font-variant |
| fontWeight | 字体粗细 | 对应 font-weight |
| fontSize | 字体大小 | 对应 font-size |
| fontFamily | 字体系列 | 对应 font-family |
| autoRotate | 是否自动旋转 | |
## 案例
```javascript
const data = {
nodes: [
{
id: 'node1',
x: 100,
y: 100,
shape: 'rect',
label: 'rect'
}
]
}
const graph = new G6.Graph({
container: 'mountNode',
width: 500,
height: 500
});
graph.data(data);
graph.render();
const node = graph.findById('node1')
graph.update(node, {
style: {
stroke: 'blue'
},
labelCfg: {
style: {
fill: 'red',
shadowOffsetX: 10,
shadowOffsetY: 10,
shadowColor: 'blue',
shadowBlur: 10
}
}
})
```
通过以上代码修改node中文本的样式效果如下图
<img src='https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*0xkLS5shGJUAAAAAAAAAAABkARQnAQ' alt='download' width='150'/>

View File

@ -0,0 +1,213 @@
---
title: Lock Node
order: 10
---
The functions for locking a node `lock()`, `unlock()`, and `hasLocked()` are supported by the versions from G6 V3.1.4. The locked node will not response the drag event any more. But it still can be moved while dragging and zooming the canvas. You can register a [Custom Behavior](/en/docs/manual/advanced/custom-behavior) to fix the node when dragging and zooming.
## Fix the Locked Node While Dragging
The built-in `drag-canvas` in G6 does not take the locked node into consideration. In most situations, it is a reasonable Behavior. For some special requirements that require to fix hte locked node when dragging, you can register a custom Behavior as shown bolow to achieve them.
```javascript
import G6 from '@antv/g6';
const Util = G6.Util;
const abs = Math.abs;
const DRAG_OFFSET = 10;
const body = document.body;
const ALLOW_EVENTS = [ 16, 17, 18 ];
G6.registerBehavior('drag-canvas-exclude-lockedNode', {
getDefaultCfg() {
return {
direction: 'both'
};
},
getEvents() {
return {
'canvas:mousedown': 'onMouseDown',
'canvas:mousemove': 'onMouseMove',
'canvas:mouseup': 'onMouseUp',
'canvas:click': 'onMouseUp',
'canvas:mouseleave': 'onOutOfRange',
keyup: 'onKeyUp',
keydown: 'onKeyDown'
};
},
updateViewport(e) {
const origin = this.origin;
const clientX = +e.clientX;
const clientY = +e.clientY;
if (isNaN(clientX) || isNaN(clientY)) {
return;
}
let dx = clientX - origin.x;
let dy = clientY - origin.y;
if (this.get('direction') === 'x') {
dy = 0;
} else if (this.get('direction') === 'y') {
dx = 0;
}
this.origin = {
x: clientX,
y: clientY
};
// The difference to built-in drag-canvas:
const lockedNodes = this.graph.findAll('node', node => !node.hasLocked());
lockedNodes.forEach(node => {
node.get('group').translate(dx, dy);
});
this.graph.paint();
},
onMouseDown(e) {
if (this.keydown) {
return;
}
this.origin = { x: e.clientX, y: e.clientY };
this.dragging = false;
},
onMouseMove(e) {
if (this.keydown) {
return;
}
e = Util.cloneEvent(e);
const graph = this.graph;
if (!this.origin) { return; }
if (this.origin && !this.dragging) {
if (abs(this.origin.x - e.clientX) + abs(this.origin.y - e.clientY) < DRAG_OFFSET) {
return;
}
if (this.shouldBegin.call(this, e)) {
e.type = 'dragstart';
graph.emit('canvas:dragstart', e);
this.dragging = true;
}
}
if (this.dragging) {
e.type = 'drag';
graph.emit('canvas:drag', e);
}
if (this.shouldUpdate.call(this, e)) {
this.updateViewport(e);
}
},
onMouseUp(e) {
if (this.keydown) {
return;
}
if (!this.dragging) {
this.origin = null;
return;
}
e = Util.cloneEvent(e);
const graph = this.graph;
if (this.shouldEnd.call(this, e)) {
this.updateViewport(e);
}
e.type = 'dragend';
graph.emit('canvas:dragend', e);
this.endDrag();
},
endDrag() {
if (this.dragging) {
this.origin = null;
this.dragging = false;
// Check whether it exists mouseup event outside. Unbind it if it exists.
const fn = this.fn;
if (fn) {
body.removeEventListener('mouseup', fn, false);
this.fn = null;
}
}
},
// If user move the mouse out of the canvas when dragging, the drag event might not be ended by releasing the mouse. Thus, listen to the mouseup event ouside the canvas to end it.
onOutOfRange(e) {
if (this.dragging) {
const self = this;
const canvasElement = self.graph.get('canvas').get('el');
const fn = ev => {
if (ev.target !== canvasElement) {
self.onMouseUp(e);
}
};
this.fn = fn;
body.addEventListener('mouseup', fn, false);
}
},
onKeyDown(e) {
const code = e.keyCode || e.which;
if (!code) {
return;
}
if (ALLOW_EVENTS.indexOf(code) > -1) {
this.keydown = true;
} else {
this.keydown = false;
}
},
onKeyUp() {
this.keydown = false;
}
});
```
## Fix the Locked Node While Zooming
Built-in Behavior `zoom-canvas` zooms all the nodes including locked nodes. Register a custom Behavior to fix the locked nodes.
```javascript
const DELTA = 0.05;
G6.registerBehavior('zoom-canvas-exclude-lockedNode', {
getDefaultCfg() {
return {
sensitivity: 2,
minZoom: 0.1,
maxZoom: 10
};
},
getEvents() {
return {
wheel: 'onWheel'
};
},
onWheel(e) {
e.preventDefault();
if (!this.shouldUpdate.call(this, e)) {
return;
}
const graph = this.graph;
const canvas = graph.get('canvas');
const point = canvas.getPointByClient(e.clientX, e.clientY);
const sensitivity = this.get('sensitivity');
let ratio = graph.getZoom();
// To be Compatible with IE, Firefox, and Chrome
if (e.wheelDelta < 0) {
ratio = 1 - DELTA * sensitivity;
} else {
ratio = 1 + DELTA * sensitivity;
}
const zoom = ratio * graph.getZoom();
if (zoom > this.get('maxZoom') || zoom < this.get('minZoom')) {
return;
}
graph.zoom(ratio, { x: point.x, y: point.y });
const lockedNodes = this.graph.findAll('node', node => !node.hasLocked());
lockedNodes.forEach(node => {
const matrix = Util.clone(node.get('group').getMatrix());
const center = node.getModel();
Util.mat3.translate(matrix, matrix, [ -center.x, -center.y ]);
Util.mat3.scale(matrix, matrix, [ ratio, ratio ]);
Util.mat3.translate(matrix, matrix, [ center.x, center.y ]);
node.get('group').setMatrix(matrix);
});
graph.paint();
graph.emit('wheelzoom', e);
}
});
```

Some files were not shown because too many files have changed in this diff Show More