我对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具有拖动功能,但我不太确定如何实现它。任何人都可以帮助我吗?
答案 0 :(得分: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]));
}
}