d3.js从javascript控制台到html页面的代码

时间:2014-02-05 18:23:47

标签: javascript d3.js

我正在学习使用d3.js和教程。

在javascript控制台(Chrome)中输入以下代码,它会创建折线图。

现在如何获取此代码并使其在html页面中运行?

 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.svg.line()
                          .x(function(d) { return d.x; })
                          .y(function(d) { return d.y; })
                         .interpolate("linear");

//The SVG Container
var svgContainer = d3.select("body").append("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");

1 个答案:

答案 0 :(得分:2)

  1. 创建名为yourfile.html的文件。
  2. 添加htmlheadbody等基本代码。
  3. script标记中添加d3 JavaScript,其中包含src="http://d3js.org/d3.v3.min.js"
  4. 将上面的代码添加到另一个scriptbody代码的末尾。
  5. 在浏览器中打开yourfile.html
  6. 总而言之,您的文件可能如下所示:

    <!DOCTYPE html>
    <html>
    <head>
        <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    </head>
    <body>
        <script type="text/javascript">
            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.svg.line().x(function(d) { return d.x; }).y(function(d) { return d.y; }).interpolate("linear");
    
            //The SVG Container
            var svgContainer = d3.select("body").append("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");
        </script>
    </body>
    </html>