如何在2个或更多点之间画线? (点数可以动态更改)

时间:2015-05-27 09:18:09

标签: javascript jquery html d3.js

我对d3.js很新,需要一些帮助。我想在2点之间划一条线。我的问题是一切都应该是动态的,即我们通常遵循告诉x1x2y1y3职位的规则。这是一个例子

var canvas = d3.select("body")
                    .append("svg")
                    .attr("width", 500)
                    .attr("height", 500);

var line = canvas.append("line")
                 .attr("x1", 0) // x1 position
                 .attr("y1", 100) // y1 position
                 .attr("x2", 400) // x2 position
                 .attr("y2", 400) // y2 position
                 .attr("stroke", "green")
                 .attr("stroke-width", 10);

我希望动态创建这些位置,即当我点击网页时,应该创建一个点并将其从位置拖动并将其放置在其他位置。我怎么能这样做?

谢谢

2 个答案:

答案 0 :(得分:1)

A line is a simple line between two points and is described by four required attributes.

    x1: The x position of the first end of the line as measured from the left of the screen.
    y1: The y position of the first end of the line as measured from the top of the screen.
    x2: The x position of the second end of the line as measured from the left of the screen.
    y2: The y position of the second end of the line as measured from the top of the screen.

The following is an example of the code section required to draw a line;

holder.append("line")          // attach a line
    .style("stroke", "black")  // colour the line
    .attr("x1", 100)     // x position of the first end of the line
    .attr("y1", 50)      // y position of the first end of the line
    .attr("x2", 300)     // x position of the second end of the line
    .attr("y2", 150);    // y position of the second end of the line

This will produce a line as follows;

enter image description here

The line extends from the point 100,50 to 300,150 (x1,y1 to x2,y2).

有关详细信息refer

答案 1 :(得分:0)

首先,您需要将您的行添加到svg中,就像您正在做的那样 下面的代码段:

var mySVG = d3.select("body")
                    .append("svg")
                    .attr("width", 500)
                    .attr("height", 500);

var line = mySVG.append("line")
                 .attr("class", ".line")//note: added a class to select later for dynamically updating.
                 .attr("x1", 0) // x1 position
                 .attr("y1", 100) // y1 position
                 .attr("x2", 400) // x2 position
                 .attr("y2", 400) // y2 position
                 .attr("stroke", "green")
                 .attr("stroke-width", 10);

在您的拖动结束回调中,您可以 选择 更新,如下所示。

mySVG.select(".line")
                 .attr("x1", 200) // x1 new position
                 .attr("y1", 300) // y1 new position
                 .attr("x2", 400) // x2 new position
                 .attr("y2", 400) // y2 new position
                 .attr("stroke", "green")
                 .attr("stroke-width", 10);

希望这有帮助!