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

标签 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. 创建一个名为 yourfile.html 的文件。
  2. 添加htmlheadbody 等基本标签。
  3. 使用 src="http://d3js.org/d3.v3.min.js"script 标记中包含 d3 JavaScript。
  4. 将上面的代码添加到另一个 scriptbody 标记的末尾。
  5. 在浏览器中打开 yourfile.html

总而言之,您的文件可能如下所示:

<!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>

关于javascript - d3.js 代码从 javascript 控制台到 html 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21585372/

相关文章:

javascript - 很难理解 d3.range.js 和 d3.scale.linear

c# - 在 httppost 之后关闭模式窗口

d3.js - d3 - 查看特定 x,y 位置的内容

json - 我们可以在 Cubism 上使用自定义 JSON 数据吗?

d3.js - 如何在 D3.js 中更改蜂群图中点的大小

javascript - 如何根据数据点索引更改元素绘制顺序?

Javascript 原型(prototype)函数和 SVG setAttribute(onclick)

javascript - javascript onClick参数中的特殊字符

javascript - JS错误: <parameter>.包含不是一个函数,不知道为什么

javascript - Socket.IO 适配器在 MongoDB 断开连接时抛出无法捕获的超时错误