【问题标题】:Javascript and D3 error: Cannot read property 'cloud' of undefinedJavascript 和 D3 错误:无法读取未定义的属性“云”
【发布时间】:2021-03-19 18:52:12
【问题描述】:

我在使用 JavaScript 和 D3 创建词云时遇到问题。弹出一个错误说“未捕获(承诺)类型错误:无法读取未定义的属性'云'”。

我对 JS 不够熟悉,无法理解如何解决这个问题(我只使用 JS,因为这是一个类分配)。我将不胜感激有关此事的一些指导。

基本上,我想在我的 CSV 文件中获取每个条目的名称,并根据其中一个数字条目将名称写入词云中。其中一些条目是负数,所以我设置为等于 1pt 字体。 下面,我附上了应该创建词云的功能代码。失败后,我查了一个教程,这段代码和我找到的教程几乎一样,所以我不明白为什么它不起作用。

我使用的是 D3 版本 5

<script src="http://d3js.org/d3.v5.min.js" charset="utf-8"></script>

这是教程建议使用的库:

<script src="https://cdn.jsdelivr.net/gh/holtzy/D3-graph-gallery@master/LIB/d3.layout.cloud.js"></script>
//define margins
var margin = {top: 40, right: 40, bottom: 100, left: 100},
width = 760 - margin.left - margin.right,
height = 760 - margin.top - margin.bottom;

// add the svg object to the body of the page
var svg = d3.select("#my_div").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

d3.csv("/data/a1-mutualFunds.csv", function(data){

  // Constructs a new cloud layout instance
  var designLayout = d3.layout.cloud()
    .size([width, height])
    .words(data.map(function(d) { return {text: d.Name, size:d.ytd}; }))
    .padding(5)        //space between words
    .rotate(function() { return ~~(Math.random() * 2) * 90; })
    .fontSize(function(d) { 
      if(d.ytd<0){return 1;}
      return d.ytd; })      // font size of words
    .on("end", draw);
  designLayout.start();

  // Draw the words
  function draw(words) {
    svg
      .append("g")
        .attr("transform", "translate(" + designLayout.size()[0] / 2 + "," + designLayout.size()[1] / 2 + ")")
        .selectAll("text")
          .data(words)
        .enter().append("text")
          .style("font-size", function(d) { return d.ytd; })
          .style("fill", "#69b3a2")
          .attr("text-anchor", "middle")
          .style("font-family", "Impact")
          .attr("transform", function(d) {
            return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
          })
          .text(function(d) { return d.text; });
}
})

【问题讨论】:

  • 我实际上无法让我的 5 个表中的 3 个正常工作,但我现在专注于这个 (^_^')
  • 错误表明d3.layout 未定义。我对 d3 不熟悉,因此无法进一步帮助您,但这可能是您应该开始寻找的地方。
  • 请说明您使用的是哪个版本的 D3,以及您使用的云库(词云不是普通 D3.js 的一部分,而是使用单独的库/插件)。跨度>
  • 刚刚将其添加到说明中。感谢您指出我没有提供该信息!
  • 如果你调用 d3.cloud 而不是 d3.layout.cloud 会发生什么?在 d3 版本 4 之前,d3 模块的组织方式不同。从 v4 开始,所有模块和插件都被称为 d3.x,没有嵌套

标签: javascript html css d3.js runtime-error


【解决方案1】:

如之前的答案所述,原因是新版本的 d3 与模块的工作方式不同。

我通过直接导入和使用 d3-cloud 使其与 d3 v6 一起使用

import * as cloud from 'd3-cloud';


var designLayout = cloud()

而不是

var designLayout = d3.layout.cloud()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-26
    • 2022-09-23
    • 2021-02-22
    • 2018-04-06
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 2017-05-21
    相关资源
    最近更新 更多