我開發了一個顯示 d3 對角樹的小程式。圖形可通過拖動背景進行導航。
它基于以下鏈接中的代碼:
見這里:https : //jsfiddle.net/chrisclarkson100/opfq6ve8/28/
我將線條附加到圖表中,如下所示:
var data_line = [
{
'x1': 300,
'y1': 700,
'x2': 300,
'y2': 700
},
////....
];
// Generating the svg lines attributes
var lineAttributes = {
....
'x1': function(d) {
return d.x1;
},
'y1': function(d) {
return screen.availHeight;
},
'x2': function(d) {
return d.x2;
},
'y2': function(d) {
return 0;
}
};
var drag_line = d3.behavior.drag()
.origin(function(d) { return d; })
.on('drag', dragged_line);
// Pointer to the d3 lines
var svg = d3.select('body').select('svg');
var lines = svg
.selectAll('line')
.data(data_line)
.enter().append('g')
.attr('class', 'link');
links_lines=lines.append('line')
.attr(lineAttributes)
.call(drag_line);
lines.append('text')
.attr('class','link_text')
.attr("x", d => d.x1)
.attr("y", d => 350)
.style('fill', 'darkOrange')
.style("font-size", "30px")
function dragged_line() {
var x = d3.event.dx;
var y = d3.event.dy;
var line = d3.select(this);
// Update the line properties
var attributes = {
x1: parseInt(line.attr('x1')) x,
y1: parseInt(line.attr('y1')) y,
x2: parseInt(line.attr('x2')) x,
y2: parseInt(line.attr('y2')) y,
};
line.attr(attributes);
}
線條顯示為我想要的并且是可拖動的。但是,當我拖動它們時,背景/樹網路會隨之移動……我希望不同的可拖動元素相互獨立。
任何人都可以發現我無法使每個元素的拖動互動性相互獨立嗎?
uj5u.com熱心網友回復:
這是一個 JSFiddle,它似乎可以做你想做的事——你可以在不移動樹的情況下移動垂直線;并在不移動垂直線的情況下移動樹:
https://jsfiddle.net/adamfeuer/gd4ouvez/125/
(該 JSFiddle 使用了一個小得多的樹節點資料集;您鏈接的那個資料集太大而無法輕松迭代和除錯。)
您發布的代碼的問題是樹的縮放(平移)功能在線條的縮放()處于活動狀態的同時處于活動狀態,因此樹和活動線同時拖動。
我添加了一個簡單的機制來將兩者分開——一個名為lineDragActive. 然后代碼在樹 zoom() 中檢查它,當拖動開始時將其設定為 true,當拖動結束時設定為 false:
// Define the zoom function for the zoomable tree
// flag indicates if line dragging is active...
// if so, we don't want to drag the tree
var lineDragActive = false;
function zoom() {
if (lineDragActive == false) {
// not line dragging, so we can zaoom (drag) the tree
svgGroup.attr("transform", "translate(" d3.event.translate ")scale(" d3.event.scale ")");
}
}
[...]
function drag_linestarted() {
// tell others not to zoom while we are zooming (dragging)
lineDragActive = true;
d3.select(this).classed(activeClassName, true);
}
function drag_lineended() {
// tell others that zooming (dragging) is allowed
lineDragActive = false;
d3.select(this).classed(activeClassName, false);
label = baseSvg.selectAll('.link_text').attr("transform", "translate(" String(Number(this.x1.baseVal.value) - 400) "," 0 ")");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/325990.html
下一篇:附加標簽未出現在圖表d3.js中
