https://antv-2018.alipay.com/zh-cn/g6/3.x/demo/tool/focus-center.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>点击节点移动到中心</title>
<style>::-webkit-scrollbar{display:none;}html,body{overflow:hidden;margin:0;}</style>
</head>
<body>
<div id="mountNode"></div>
<script>/*Fixing iframe window.innerHeight 0 issue in Safari*/document.body.clientHeight;</script>
<script src="https://gw.alipayobjects.com/os/antv/pkg/_antv.g6-3.1.1/build/g6.js"></script>
<script>
/**
* 演示聚焦(focus)和动画
* by 长哲
*/
function initGraph() {
var data = {
nodes: [{
id: 'node1',
x: 150,
y: 50,
label: 'node1'
}, {
id: 'node2',
x: 200,
y: 150,
label: 'node2'
}, {
id: 'node3',
x: 100,
y: 150,
label: 'node3'
}],
edges: [{
source: 'node1',
target: 'node2'
}, {
source: 'node2',
target: 'node3'
}, {
source: 'node3',
target: 'node1'
}]
};
var graph = new G6.Graph({
container: 'mountNode',
width: window.innerWidth,
height: window.innerHeight,
fitView: false
});
graph.data(data);
graph.render();
return graph;
}
function handleNodeClick(event) {
var item = event.item;
// 聚焦当前点击的节点(把节点放到视口中心)
var matrix = item.get('group').getMatrix();
var point = {
x: matrix[6],
y: matrix[7]
};
var width = graph.get('width');
var height = graph.get('height');
// 找到视口中心
var viewCenter = {
x: width / 2,
y: height / 2
};
var modelCenter = graph.getPointByCanvas(viewCenter.x, viewCenter.y);
var viewportMatrix = graph.get('group').getMatrix();
// 画布平移的目标位置,最终目标是graph.translate(dx, dy);
var dx = (modelCenter.x - point.x) * viewportMatrix[0];
var dy = (modelCenter.y - point.y) * viewportMatrix[4];
var lastX = 0;
var lastY = 0;
var newX = void 0;
var newY = void 0;
// 动画每次平移一点,直到目标位置
graph.get('canvas').animate({
onFrame: function onFrame(ratio) {
newX = dx * ratio;
newY = dy * ratio;
graph.translate(newX - lastX, newY - lastY);
lastX = newX;
lastY = newY;
}
}, 300, 'easeCubic');
}
var graph = initGraph();
// 监听节点上的click事件
graph.on('node:click', handleNodeClick);
</script></body>
</html>
文档更新时间: 2024-04-05 16:11 作者:admin