使用d3js的{Word-Cloud

时间:2018-04-08 05:36:36

标签: javascript html d3.js d3-cloud

我正在尝试使用GitHub上提供的d3js源代码来绘制WordCloud GitHub

我的index.html文件如下:

<html xmlns="html">
    <head>
        <title>Visualization Medley</title>
        <link rel="stylesheet" 
      href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="medley.css">
</head>
<body>
<div class="container">
<h3>Word Cloud</h3>
<div id="world-cloud"></div>
</div>

<script type="text/javascript" src="https://d3js.org/d3.v3.min.js"/><\script>
<script type="text/javascript" src="C:/Users/xxx/Desktop/d3.layout.js"/><\script>
<script type="text/javascript" src="C:/Users/xxx/Desktop/medley.js"/> 
<\script>
</body>
</html>

我的d3.layout.js文件包含以下代码:
Source Code

我的medley.js源代码:
Source Code

当我打开index.html文件时,它没有显示默认的wordcloud。谁能告诉我哪里出错了?
我以前没有编写JavaScript / HTML代码的经验。

1 个答案:

答案 0 :(得分:2)

以下是显示云的代码的略微修改版本:

&#13;
&#13;
var fill = d3.scale.category20();

var layout = d3.layout.cloud()
    .size([500, 500])
    .words([
      "Hello", "world", "normally", "you", "want", "more", "words",
      "than", "this"].map(function(d) {
      return {text: d, size: 10 + Math.random() * 90, test: "haha"};
    }))
    .padding(5)
    .rotate(function() { return ~~(Math.random() * 2) * 90; })
    .font("Impact")
    .fontSize(function(d) { return d.size; })
    .on("end", draw);

layout.start();

function draw(words) {
  d3.select("body").append("svg")
      .attr("width", layout.size()[0])
      .attr("height", layout.size()[1])
    .append("g")
      .attr("transform", "translate(" + layout.size()[0] / 2 + "," + layout.size()[1] / 2 + ")")
    .selectAll("text")
      .data(words)
    .enter().append("text")
      .style("font-size", function(d) { return d.size + "px"; })
      .style("font-family", "Impact")
      .style("fill", function(d, i) { return fill(i); })
      .attr("text-anchor", "middle")
      .attr("transform", function(d) {
        return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
      })
      .text(function(d) { return d.text; });
}	
&#13;
<html xmlns="html">
    <head>
        <title>Visualization Medley</title>
        <link rel="stylesheet" 
      href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="medley.css">
</head>
<body>
<div class="container">
<h3>Word Cloud</h3>
<div id="world-cloud"></div>
</div>

<script type="text/javascript" src="https://d3js.org/d3.v3.min.js"/></script>
<script type="text/javascript" src="https://cdn.rawgit.com/jasondavies/d3-cloud/master/build/d3.layout.cloud.js"/></script>
</body>
</html>
&#13;
&#13;
&#13;

我首先将依赖项修改为jasondavies/d3-cloud

<script type="text/javascript" src="https://cdn.rawgit.com/jasondavies/d3-cloud/master/build/d3.layout.cloud.js"/></script>

最不可能导致图表不显示的原因是对云的调用,应该是:

var layout = d3.layout.cloud().size([500, 500]).words([...

而不是:

var layout = cloud().size([500, 500]).words([...