D3如何在mousedown事件中触发拖动?

3

有没有一种方法可以在svg的任何位置单击,并使元素定位到该位置并同时开始拖动?

我已经接近实现了下面的代码。拖动圆形是有效的,而单击其他位置会使圆形移动到那个位置,但我无法想出如何在不释放鼠标并直接单击圆形的情况下开始拖动。

更一般地说,如何在不直接与要拖动的元素交互的情况下开始拖动行为?

http://jsfiddle.net/Hj44M/1/

var width = 200,
    height = 200,
    radius = 10;

var drag = d3.behavior.drag()
    .origin(function(d) { return d; })
    .on("dragstart", function(){
        d3.event.sourceEvent.stopPropagation()
    })
    .on("drag", dragmove);

var svg = d3.select("body")
    .data([{x: 100, y : 100}])
    .append('svg')
    .attr("height", 200)
    .attr("widht", 200)
    .on("mousedown", function(){
        circle.each(dragmove)
    });


var circle = svg.append("circle")
    .attr("r", radius)
    .attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; })
    .call(drag);

function dragmove(d) {
    d3.select(this)
    .attr("cx", d.x = Math.max(radius, Math.min(width - radius, d3.event.x)))
    .attr("cy", d.y = Math.max(radius, Math.min(height - radius, d3.event.y)));
}

听起来你想在 SVG 上添加一个点击事件处理程序,将圆形移动到点击的位置。 - Lars Kotthoff
1个回答

5

更新

我通过一种类似于暴力的解决方案解决了这个问题:我移除了拖拽行为,只是添加了mousedown、mousemove和mouseup事件处理程序到svg画布中。这是我想要的功能,但我仍然希望使用d3的拖拽行为。如果有更优雅的解决方案,请告诉我。

http://jsfiddle.net/Hj44M/5/

    var width = 200,
    height = 200,
    radius = 10;

var isDown = false;

var svg = d3.select("body")
    .data([{x: 100, y : 100}])
    .append('svg')
    .attr("height", 200)
    .attr("width", 200)
    .on("mousedown", function(){
        isDown = true;  
        var coordinates = d3.mouse(this);
        circle.each(function(d){
            circle.attr("cx", d.x = coordinates[0])
            circle.attr("cy", d.y = coordinates[1])
        })

    })
    .on("mousemove", function(){
        if(isDown) {
            var coordinates = d3.mouse(this);
            circle.each(function(d){
                circle.attr("cx", d.x = coordinates[0])
                circle.attr("cy", d.y = coordinates[1])
            })
        }
     })
    .on("mouseup", function(){
        isDown = false;
    });     

var circle = svg.append("circle")
    .attr("r", radius)
    .attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接