如何在两个或多个点之间画线?(积分可以动态变化)

How to draw lines between 2 or more points ? (Points can be changed dynamically)

本文关键字:变化 动态 两个 之间      更新时间:2023-09-26

我是d3.js的新手,需要一些帮助。我试着在两点之间画一条线。我的问题是一切都应该是动态的,即我们通常遵循告诉x1, x2, y1y3位置的规则。下面是一个例子

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);

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

谢谢

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).

详情请参考

因此,首先您需要将行附加到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);

希望这对你有帮助!