[英]d3js zoom + drag causes conflict
我正在嘗試將縮放行為應用於svg,其中svg中的某些元素已經綁定了拖動行為。 如果沒有縮放行為,則拖動效果很好,如果沒有拖動行為,則縮放效果很好。 當我同時擁有它們時,就會發生沖突。 當我拖動一個圓時,所有其他圓都開始隨之拖動。
這是小提琴 。
誰能幫我解決這個問題?
<svg height="600" width="600" style="background: black">
<g>
<rect x="0" y="0" , width="600" height="40" style="fill:gold;"></rect>
<circle id='drag' cx="15" cy="20" init-cx="15" init-cy="20" r="10"
style="stroke: white; stroke-width: 2px; fill:blue"/>
</g>
<g id="playground">
<g>
<circle class='top' cx="180" cy="120" r="30" style="stroke: white; stroke-width: 2px; fill:white"/>
</g>
<g>
<circle class='top' cx="200" cy="220" r="30" style="stroke: white; stroke-width: 2px; fill:white"/>
</g>
<g>
<circle class='top' cx="320" cy="150" r="50" style="stroke: white; stroke-width: 2px; fill:white"/>
</g>
</g>
var zoom = d3.behavior.zoom()
.scaleExtent([-1, 8])
.on("zoom", function () {
var graph = d3.select('svg');
graph
.select('#playground')
.selectAll('circle')
.select(function () {
return this.parentNode;
})
.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
});
var move = d3.behavior.drag()
.on('drag', function () {
console.log('dragging');
var curr = d3.select(this)
.attr({
cx: d3.mouse(this)[0],
cy: d3.mouse(this)[1]
})
})
.on('dragend', function () {
var curr = d3.select(this);
d3.select('#playground')
.append('circle')
.attr({
cx: curr.attr('cx'),
cy: curr.attr('cy'),
r: curr.attr('r')
})
.style({
fill: 'white',
stroke: 'red',
'stroke-width': '2px'
})
;
curr.attr({
cx: curr.attr('init-cx'),
cy: curr.attr('init-cx')
});
})
;
d3.select('#drag').call(move);
d3.select('.top')
.call(d3.behavior.drag().on('drag', function () {
d3.select(this)
.attr({
cx: d3.mouse(this)[0],
cy: d3.mouse(this)[1]
})
;
}));
d3.select('svg').call(zoom);
我已經實現了單個拖動節點以及整體縮放和平移功能。 在圓的dragstart
事件中使用了事件的stopPropagation
。
希望這可以幫助。
var move = d3.behavior.drag()
.on("dragstart", function() {
d3.event.sourceEvent.stopPropagation();
});
工作中的JSFiddle
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.