0

Code taken from Live drawing of a line in D3.js

var line;

var vis = d3.select("body").append("svg") 
    .attr("width", 600)
    .attr("height", 400)
    .on("mousedown", mousedown)
    .on("mouseup", mouseup);

function mousedown() {
    var m = d3.mouse(this);
    line = vis.append("line")
        .attr("x1", m[0])
        .attr("y1", m[1])
        .attr("x2", m[0])
        .attr("y2", m[1]);

    vis.on("mousemove", mousemove);
}

function mousemove() {
    var m = d3.mouse(this);
    line.attr("x2", m[0])
        .attr("y2", m[1]);
}

function mouseup() {
    vis.on("mousemove", null);
}

How do I know if the user clicks on a previously appended line? In the mousedown() function I only want a new line appended if the user is clicking on the svg, and not a line appended to the svg.

Essentially, in the mousedown() function, how do you say that if m != line, then continue appending a line?

Community
  • 1
  • 1

1 Answers1

0

@michael you can do something like this to know if its a line or svg on which the user has clicked.

function mousedown() {
    var m = d3.mouse(this);
    line = vis.append("line")
        .attr("x1", m[0])
        .attr("y1", m[1])
        .attr("x2", m[0])
        .attr("y2", m[1]);
    if (d3.event.srcElement.tagName == "svg"){
        //handle svg
    } else if (d3.event.srcElement.tagName == "line"){
        //handle line
    }
    vis.on("mousemove", mousemove);
}
Cyril Cherian
  • 32,177
  • 7
  • 46
  • 55
  • Thanks, I have a follow up if you can help. Now the whole line is modifiable (which is great), but only if the line is not at the starting point. Is there an easy way to get the behavior at the endpoint of the line at the starting point as well? Here is my jfiddle: http://jsfiddle.net/da37B/303/ – Michael Richter Jul 16 '15 at 04:25
  • What do you mean when you say the "line is not at the starting point" are you saying that you want to extend the line from the end? – Cyril Cherian Jul 16 '15 at 04:54
  • No, in my jsfiddle when the line is clicked on, it can be modified but the starting point stays the same. If I click near the starting point of the line, is there a way to change the starting point to the endpoint of the line, meaning it can now be modified the other way? Also, your solution works for one line, but if there are many lines the behavior only applies to the last drawn line. Sorry if this is confusing, but I very much appreciate the help. – Michael Richter Jul 16 '15 at 05:47
  • @MichaelRichter to the second problem that the last line created is always getting updated, you were not setting the line variable .I have done it here http://jsfiddle.net/cyril123/waszdyhg/1/ check teh else if block. – Cyril Cherian Jul 16 '15 at 06:57
  • Thanks again for the help. Works great. First problem may be pretty difficult. – Michael Richter Jul 16 '15 at 07:19