我正在尝试画一条一端带有箭头的线。另外,我需要对同一图中的多个箭头自动执行此操作。
d3.csv("/data/coordinates.csv").then(function(data) {
d.x1= +d.x1;
d.y1= +d.y1;
d.x2= +d.x2;
d.y2= +d.y2;
});
所以输入就像
x1,y1,x2,y2
1,2,3,2
3,3,5,4
5,3,6,3
7,5,7,5
8,6,8,6
9,7,2,8
var xoneValue = function(d) { return d.x1;},
xoneMap = function(d) { return xoneValue(d);};
var yoneValue = function(d) { return d.y1;},
yoneMap = function(d) { return yoneValue(d);};
var xtwoValue = function(d) { return d.x2;},
xtwoMap = function(d) { return xtwoValue(d);};
var ytwoValue = function(d) { return d.y2;},
ytwoMap = function(d) { return ytwoValue(d);};
我找到了以下代码,但是当数据在文件中时,我如何循环遍历此代码?
holder.append("line") // attach a line
.style("stroke", "black") // colour the line
.attr("x1", xoneMap ) // x position of the first end of the line
.attr("y1", xtwoMap ) // y position of the first end of the line
.attr("x2", xtwoMap ) // x position of the second end of the line
.attr("y2", ytwoMap ); // y position of the second end of the line
最佳答案
您所需要的只是一个enter selection 。例如:
const enterSelection = svg.selectAll(null)
.data(data)
.enter()
.append("line")
//etc...
顺便说一句,所有这些行......
var xoneValue = function(d) { return d.x1;},
xoneMap = function(d) { return xoneValue(d);};
...没有做任何事情,他们只是按原样重新调整值。另外,您尝试创建行函数...
d.x1= +d.x1;
d.y1= +d.y1;
d.x2= +d.x2;
d.y2= +d.y2;
...不正确。在 d3.csv
内执行此操作。
这是一个包含您的数据的演示(由于所有坐标都非常小并且没有比例,因此我将 SVG 与 viewBox
结合使用):
const csv = `x1,y1,x2,y2
1,2,3,2
3,3,5,4
5,3,6,3
7,5,7,5
8,6,8,6
9,7,2,8`;
const data = d3.csvParse(csv, function(d) {
d.x1 = +d.x1;
d.y1 = +d.y1;
d.x2 = +d.x2;
d.y2 = +d.y2;
return d;
});
const svg = d3.select("svg");
const enterSelection = svg.selectAll(null)
.data(data)
.enter()
.append("line")
.attr("x1", d => d.x1)
.attr("y1", d => d.y1)
.attr("x2", d => d.x2)
.attr("y2", d => d.y2)
.style("stroke-width", "1px")
.style("stroke", "black")
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg viewBox="0 0 20 20"></svg>
关于javascript - 如何通过从文件读取坐标自动画线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55251989/