I am beginner with D3 and I am trying to drag with mouse a rectangle but actually I experience some troubles.
If I define var drag before to call it get this error: Cannot read property 'drag' of undefined
If I define var drag after calling it, I get a different error: Cannot read property 'apply' of undefined But actually, searching on stackoverflow I read that to solve this probl I need to define the var drag before to call it and I am on a loop.
Below you can see my code. Thanks in advance.
$(document).ready(function() {
var width = 500;
var height = 500;
var fullAngle = 2 * Math.PI;
var arc2 = d3.arc()
.innerRadius(195)
.outerRadius(200)
.startAngle(0.18)
.endAngle(fullAngle / 1.02);
var svgContainer = d3.select("#container")
.append("svg")
.attr("width", width)
.attr("height", height)
.style("border", "1px solid");
var group1 = svgContainer.append("g");
var group2 = svgContainer.append("g");
group2.append("path")
.attr("d", arc2())
.attr("fill", "blue")
group1.attr("transform", "translate(" + 200 + "," + 200 + ")");
group2.attr("transform", "translate(" + 250 + "," + 250 + ")");
var rectangle = svgContainer.append("rect")
.attr("x", 150)
.attr("y", 50)
.attr("width", 30)
.attr('class', 'rectangle')
.attr("height", 70)
.call(drag)
var drag = d3.behavior.drag().on('drag', function () {
var obj = svgContainer.append("rect")
dragMove(this, obj, 'rect')
});
});
function setPoints(obj, prop) {
obj[prop] = []
var k = 0
d3.selectAll('.rect')
.each(function() {
var c = d3.select(this)
var cX = d3.transform(c.attr('transform')).translate[0]
var cY = d3.transform(c.attr('transform')).translate[1]
obj[prop].push({
x: cX,
y: cY,
index: k++
})
})
}
function dragMove(rectangle, obj, prop) {
var x = d3.event.x
var y = d3.event.y
setPoints(obj, prop)
d3.select(rectangle).attr('transform', 'translate(' + x + ',' + y + ')')
$scope.$apply()
}
You are using d3 v4 in your code.
d3.behavior.drag() is changed to d3.drag you function should be like this and declared before usage
var drag = d3.drag().on("drag", function () {
d3.event.sourceEvent.stopPropagation(); // silence other listeners
dragMove(this, obj, 'points')
})
Implement your dragMove function to continue See this FIDDLE
You are using D3 v4, and like many other things, the drag behavior has been renamed. From the changelog:
The drag behavior d3.behavior.drag has been renamed to d3.drag.
You need to adjust your code for this renaming.
var drag = d3.drag().on('drag', function () {
dragMove(this, obj, 'points')
});
Since the implementation did also change, there may be other changes required to make it actually work. This however is not clear from the code you provided and will well be worth another question.