在下面的例子中,我使用lineFunction绘制路径的坐标。我希望正确输入代码,仍然面临错误。有人可以帮忙吗?
SNIPPET:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js"></script>
<script>
$(document).ready(function(){
//our basic data
var customData = [
{"x": 100, "y": 100},
{"x": 200, "y": 50},
{"x": 300, "y": 150},
{"x": 400, "y": 20}
];
//the line function for path
var lineFunction = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("linear");
//Main svg container
var mySVG = d3.select("svg");
//defining the lines
var path = mySVG.append("path");
//plotting lines
path
.attr("d", lineFunction(customData))
.attr("stroke",function() { return "hsl(" + Math.random() * 360 + ",100%,50%)"; })
.attr("stroke-width", 2)
.attr("fill", "none");
});
</script>
</head>
<body>
<svg width="500px" height="500px"></svg>
</body>
</html>
错误:
var lineFunction = d3.svg.line() //error here ...
答案 0 :(得分:3)
看起来版本问题对我来说看看 -
$(document).ready(function(){
//our basic data
var customData = [
{"x": 100, "y": 100},
{"x": 200, "y": 50},
{"x": 300, "y": 150},
{"x": 400, "y": 20}
];
//the line function for path
var lineFunction = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("linear");
//Main svg container
var mySVG = d3.select("svg");
//defining the lines
var path = mySVG.append("path");
//plotting lines
path
.attr("d", lineFunction(customData))
.attr("stroke",function() { return "hsl(" + Math.random() * 360 + ",100%,50%)"; })
.attr("stroke-width", 2)
.attr("fill", "none");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="//d3js.org/d3.v3.min.js"></script></script>
<svg width="500px" height="500px"></svg>
答案 1 :(得分:1)
正如Chetan已经提到的,它是你所包含的D3文件的版本问题。您包括D3 V4但使用D3 V3的语法。
在V4中,他们删除了d3.svg。所以你需要做的就是将d3.svg.line()更改为d3.line(),它应该可以工作。
参考:d3.svg.line() error: Uncaught TypeError: Cannot read property 'line' of undefined
EDIT-1:试试这段代码片段
var svg;
//The data for our line
var lineData = [ { "x": 1, "y": 5}, { "x": 20, "y": 20},
{ "x": 40, "y": 10}, { "x": 60, "y": 40},
{ "x": 80, "y": 5}, { "x": 100, "y": 60}];
//This is the accessor function we talked about above
var lineFunction = d3.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; });
//The SVG Container
var svgContainer = d3.select("body").append("svg:svg")
.attr("width", 200)
.attr("height", 200);
//The line SVG Path we draw
var lineGraph = svgContainer.append("path")
.attr("d", lineFunction(lineData))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none");