2016-03-03 100 views
0

我有一種情況,我正在創建一個視圖窗格,路徑「內部」它。爲了給人留下深刻的印象,我正在剪輯它們。我也想能夠拖動這些路徑。通常的建議是使用SVG transform屬性。但是,這提出了兩個問題:使用D3拖動路徑

  • 剪輯路徑保持下去,而只對部分路徑顯示
  • 拖路徑「漂浮」在指定窗格的外拖。

完成JSFiddle

的數據是:

var outlines = [ 
[{ "x": 100.0, "y": 100.0}, {"x": 200.0, "y": 100.0}, {"x": 200.0, "y": 200.0}, {"x": 100.0,"y": 200.0}, {"x": 100.0, "y": 100.0}], 
[{ "x": -100.0, "y": 200.0}, {"x": 100.0, "y": 200.0}, {"x": 100.0, "y": 300.0}, {"x": -100.0,"y": 300.0}, {"x": -100.0, "y": 200.0}], 
]; 

我創建這樣的路徑:

layout 
.selectAll('.instance') 
.data(outlines) 
.enter() 
.append('path') 
.attr('class', 'instance') 
.attr('d', function(d) { return line(d); }) 
.call(drag); 

而且阻力是:

var drag = d3.behavior.drag() 
.origin(function(d) { 
    return { 
    x: 0, 
    y: 0 
    }; 
}) 
.on("dragstart", function(d) { 
    d3.event.sourceEvent.stopPropagation(); 
}) 
.on("drag", function(d) { 
    d3.select(this) 
    .classed("dragging", true) 
    .attr('transform', function(d) { return 'translate(' + d3.event.x + ',' + d3.event.y + ')'; }); 
}) 
.on("dragend", function(d) { 
    d3.select(this) 
    .classed("dragging", false) 
    .attr('transform', null); 
}); 

我想,我想真正移動通往新位置的路徑。但我不確定如何使用d3.event偏移量處理數據。我怎麼做?還是有更好的方法來做到這一點?

+0

你想要做這樣的事嗎? http://bl.ocks.org/mccannf/1629464 – Stargazer

+0

是的,大多數情況下,這個例子使用'rect',只需更新x/y屬性就可以輕鬆完成。我需要有一條路徑,因爲我的對象可能比我在示例中使用的矩形更復雜。我如何更新路徑?我注意到平移/縮放更新路徑。怎麼樣? –

回答

1

要正常工作,transform必須嚴格在clip-path之內(或換句話說,如果元素具有剪輯路徑和變換屬性,則剪輯路徑的座標將被移動,就像該對象的其餘部分

最簡單的方法在你的情況來解決,這是包裝剪輯path'd組內的矩形:

layout 
.selectAll('.instance') 
.data(outlines) 
.enter() 
.append("g") //this group defines the clipping 
.attr("clip-path","url(#clip)") 
.append('path') //this path can be moved around 
.attr('class', 'instance') 
.attr('d', function(d) { 
    return line(d); 
}) 
.call(drag) 

https://jsfiddle.net/xhfcdbb7/

我也刪除一個對剪輯路徑的其他參考(這樣,組仍然剪輯到相同的絕對矩形,無論它是否被拖動)

+0

就是這樣! –