【发布时间】:2018-05-30 21:09:27
【问题描述】:
我是 Cytoscape.js 的新手,到目前为止,我真的很欣赏它的功能。我的问题如下:对于我的项目,我需要创建一个用户可以修改的图表,并且我需要一个重置按钮,以便在用户首先找到它们时替换所有元素。
我使用 cose-bilkent 布局,因为我获取没有位置信息的数据。
这是我的 js 代码。
var cy = cytoscape({
container: document.getElementById('cy'),
style: [{
selector: 'node',
style: {
shape: 'roundrectangle',
'background-color': 'red',
label: 'data(id )'
}
}, ],
});
cy.on('tap', 'node', function(evt) {
var node = evt.target;
console.log("tap", node.id(), node.position());
});
cy.add([{
data: {
id: 'a'
}
},
{
data: {
id: 'b'
}
},
{
data: {
id: 'c'
}
},
{
data: {
id: 'ab',
source: 'a',
target: 'b'
}
},
{
data: {
id: 'ac',
source: 'a',
target: 'c'
}
}
]);
cy.layout({
name: 'cose-bilkent',
avoidOverlap: true,
avoidOverlapPadding: 10,
}).run();
cy.nodes().forEach(function(ele) {
console.log("loop", ele.id(), ele.position());
});
单击节点后查看控制台时,我看到以下内容:
我的问题是:为什么当我点击节点时,对象位置是正确的({x:30,y:30}),而在循环中对象是{x:0,y:0}?
编辑: 在斯蒂芬的回答之后,我将代码更改为以下内容:
var cy = cytoscape({
container: document.getElementById('cy'),
style: [
{
selector: 'node',
style: {
shape: 'roundrectangle',
'background-color': 'red',
label: 'data(id )'
}
},
],
});
cy.on('tap', 'node', function(evt) {
var node = evt.target;
console.log("tap", node.id(), node.position());
});
cy.add([
{ data: { id: 'a' } },
{ data: { id: 'b' } },
{ data: { id: 'c' } },
{
data: {
id: 'ab',
source: 'a',
target: 'b'
}
},
{
data: {
id: 'ac',
source: 'a',
target: 'c'
}
}
]);
cy.layout({
name: 'cose-bilkent',
avoidOverlap: true,
avoidOverlapPadding: 10,
}).run();
setTimeout( function() {
cy.nodes().forEach(function(ele){
console.log("loop", ele.id(), ele.position());
});
}, 2000);
// Not Working :
// cy.ready( function() {
// cy.nodes().forEach(function(ele){
// console.log("loop", ele.id(), ele.position());
// });
// });
解决方案:
最后我找到了一个更好的解决方案:我使用了事件“layoutstop”以便在正确的时刻开始复制位置:
cy.on('layoutstop', function() {
cy.nodes().forEach(function(ele){
console.log("loop", ele.id(), ele.position().x, ele.position().y);
});
});
但是,如果您使用此解决方案,您必须知道它不适用于外部函数(出于某种未知原因)。因此以下方法不起作用:
cy.on('layoutstop', copyPos());
function copyPos() {
cy.nodes().forEach(function(ele){
console.log("loop", ele.id(), ele.position().x, ele.position().y);
});
}
【问题讨论】: