I need to create a d3 group with some shapes (e.g. rect, circle, ...) in it, and I need to drag it. Drag and Drop works, but when the drag starts, the form “jumps”. I know I need something like .attr("x", d.x = d3.event.x). But then I get an error that "d" is undefined. How can I fix a jump? Here is a very simple code:
var svg = d3.select("body").append("svg")
.attr("preserveAspectRatio", "xMinYMin meet")
.attr("viewBox", "0 0 960 600")
.attr("width", "100%")
.attr("height", "100%");
rectGroup();
function rectGroup() {
var group = svg.append('g')
.attr("class", "group")
.call(d3.drag()
.on("drag", dragged));
group.append("rect")
.data([{ x: 200, y: 200, width: 100 , height: 100}])
.attr('class', 'rect')
.attr("x", function(d) { return d.x; })
.attr('y', function(d) { return d.y; })
.attr('width', function(d) { return d.width; })
.attr('height', function(d) { return d.height; });
}
function dragged(d) {
d3.select(this).select("rect").attr("x", d3.event.x)
d3.select(this).select("rect").attr("y", d3.event.y)
}
source
share