dagda1
dagda1

Reputation: 28850

d3 - apply transformations to different elements when dragging

I have the code that is in the following jsbin, I have dragging enabled for either of the circles at the end of a line.

What I want to do is move the other elements so the line moves with the circle.

How can I apply other transformations to other elements in the ondrag handler?

I just want advice and not code because this is a good learning exercise for me.

Upvotes: 0

Views: 25

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

One of the many ways:

Add a style to the circle to mark the start and end of a circle.

var line = {
    start: {x: 2, y: 3, type: "start"},
    finish: {x: 14, y: 6, type: "end"} 
  };
//adding this type to the class of the circle
var circles = g
     .selectAll('circle')
     .data(lineData)
     .enter().append("circle")
     .attr('class', function(d){return "circle "+d.type;})
     .attr('cx', function(d){return xScale(d.x);})
     .attr('cy', function(d){return yScale(d.y);})
     .attr('r', 10)
     .style('fill', 'red')
     .call(drag);

Then on drag updating the lines x1/y1 x2/y2 depending on the class of the circle dragged.

if (d3.select(this).classed("start")){
          //update the start position of line
          d3.select(".line").attr("x1", d3.event.x).attr("y1", d3.event.y);
        } else {
          d3.select(".line").attr("x2", d3.event.x).attr("y2", d3.event.y);

Full code here.

Upvotes: 1

Related Questions