2014-06-17 27 views
0

我對D3非常新,只是掌握了它。我有讓用戶在mousedown上畫圈的代碼。下面是搗鼓它:http://jsfiddle.net/amwill/HhLVt/使用戶繪製後可以拖動形狀

function getRadius(x1, y1, x2, y2) { 
return Math.sqrt((Math.pow(x2 - x1, 2) + (Math.pow(y2 - y1, 2)))); 
} 
var circle, isDown = false, m1, m2; 
var vis = d3.select("body").append("svg") 
.on("mousedown", mousedown); 
function mousedown() { 
if (!isDown) { 
    m1 = d3.mouse(this); 
    circle = vis.append("circle") 
     .attr("cx", m1[0]) 
     .attr("cy", m1[1]) 
     .attr("r", 0); 
} 
isDown = !isDown; 
vis.on("mousemove", mousemove); 
} 
function mousemove() { 
m2 = d3.mouse(this); 
if (isDown) { 
    m2 = d3.mouse(this); 
    circle.attr("r", getRadius(m1[0], m1[1], m2[0],m2[1])); 
} 
} 

但我想用戶繪製後,它有一個形狀拖動。我知道D3有拖動功能,但我不太清楚如何實現它。誰能幫我?

+1

我認爲[這](http://jsfiddle.net/iweczek/KDnVR/1/)正是你要尋找的。 –

+0

這對於這個特殊的問題有點複雜,但我認爲這對未來會有幫助。謝謝! – cocoa

+0

下面是一個可拖動的圈子http://jsfiddle.net/uAwkA/的簡單示例,以引用 – jarbaugh

回答

0

這就是我的做法,我使用了d3.behavior.drag()。 Here's the fiddle

function getRadius(x1, y1, x2, y2) { 
    return Math.sqrt((Math.pow(x2 - x1, 2) + (Math.pow(y2 - y1, 2)))); 
} 

var circle, isDown = false, cDown = false, isDragging = false, m1, m2, 
    width = 800, height = 600, cx = 0, cy = 0, radius = 0; 

var drag = d3.behavior.drag() 
.on("drag", dragmove); 

function dragmove() {  
    var initialX = this.getAttribute("cx"), initialY = this.getAttribute("cy"); 
    d3.select(this) 
     .attr("cx", +initialX + d3.event.dx) 
     .attr("cy", +initialY + d3.event.dy); 
} 

var vis = d3.select("body").append("svg").attr("width",width).attr("height",height) 
    .on("mousedown", mousedown1); 

function mousedown1() { 
    if (!isDown && !isDragging) { 
     m1 = d3.mouse(this); 
     circle = vis.append("circle") 
      .attr("cx", m1[0]) 
      .attr("cy", m1[1]) 
      .attr("r", 0) 
      .call(drag); 
} else { 
    cDown = !cDown; 
    circle.on("mousedown", mousedown2); 
    function mousedown2() { 
     isDragging = true; 
    } 
    circle.on("mouseup", mouseup); 
    function mouseup(e) { 
     isDragging = isDown = false; 
     cDown = !cDown;    
    } 
} 
isDown = !isDown;  
} 

vis.on("mousemove", mousemove); 
function mousemove() { 
    m2 = d3.mouse(this); 
    if (isDown && !isDragging) { 
     m2 = d3.mouse(this); 
     circle.attr("r", getRadius(m1[0], m1[1], m2[0],m2[1])); 
    } 
}