无法在d3js中拖动矩形。代码看起来很好。我在这里错过了什么?
所有拖动行为(如开始拖动和拖动结束)都已实现,但拖动仍无法正常工作
这是我的代码:
var svgContainer = d3.select("body").append("svg")
.attr("width", 800)
.attr("height", 803);
var rect = svgContainer.append("rect")
.attr("x", 10)
.attr("y", 50)
.attr("width", 51)
.attr("height", 41)
.attr("stroke", "#7E7E7E")
.attr("cursor", "move")
var drag = d3.behavior.drag()
.on("dragstart", dragstart)
.on("drag", drag)
.on("dragend", dragend);
function dragstart()
{
d3.event.sourceEvent.stopPropagation();
}
function drag()
{
var self = d3.select(this);
//var translate =d3.transform(self.getAttribute("transform")).translate;
var translate = d3.transform(self.attr("transform")).translate;
var x = d3.event.dx + translate[0],
y = d3.event.dy + translate[1];
self.attr("transform", "translate(" + x + "," + y + ")");
}
function dragend()
{
var mouseCoordinates = d3.mouse(this);
if (mouseCoordinates[0] > 170)
{
//Append new element
svg.append("g").append("rect")
.attr("x", mouseCoordinates[0])
.attr("y", mouseCoordinates[1])
.attr("width", 51)
.attr("height", 41)
.attr("stroke", "#7E7E7E")
.style('cursor', 'move')
.classed("initialDragRect", true)
.call(drag);
}
}
rect.call(drag);
答案 0 :(得分:0)
将函数中代码的translate
变量声明更改为此
var translate = d3.transform(self.attr("transform")).translate;
问题是因为self
变量没有函数getAttribute()