javascript 空或未定义的D3布局,用于词云生成

67up9zun  于 2023-03-28  发布在  Java
关注(0)|答案(1)|浏览(123)

我已经从D3库中转换了一个简单的例子来显示一个单词云。
即使我认为我及时创建了svg和布局,我仍然得到著名的错误消息Uncaught TypeError: Cannot read properties of undefined (reading 'cloud')
为什么会这样?我看不出我的错误。有人能帮我解决吗?谢谢

var data = ["hello", "world", "d3", "word", "cloud", "visualization"];

var svg = d3
    .select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height"),
    margin = { top: 20, right: 20, bottom: 30, left: 40 },
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// Define the word cloud layout.
var layout = d3.layout
    .cloud()
    .size([width - margin.left - margin.right, height - margin.top - margin.bottom])
    .words(data.map(function (d) { return { text: d, size: 10 + Math.random() * 40 }; }))
    .padding(5)
    .rotate(function () { return ~~(Math.random() * 2) * 90; })
    .fontSize(function (d) { return d.size; })
    .on("end", draw);

layout.start();

function draw(words) {
    g.selectAll(".word")
        .data(words)
        .join("text")
        .attr("class", "word")
        .style("font-size", function (d) { return d.size + "px"; })
        .style("fill", function (d, i) { return "steelblue"; })
        .attr("text-anchor", "middle")
        .attr("transform", function (d) {
            return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
        })
        .text(function (d) { return d.text; });
}

很明显,我的html文件包含了一些常见的东西:

<body>
    <script src="https://d3js.org/d3.v7.min.js"></script>
    <svg width="500" height="300"></svg>  
    <script src="word-cloud-script.js"></script>
</body>

我已经看到了这种错误的一些指导方针,但我没有看到我的布局为null或未定义的问题。请问是什么问题?

2izufjch

2izufjch1#

我发现我的html文件中缺少以下cdn导入:

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-cloud/1.2.5/d3.layout.cloud.js"></script>

一旦我把它添加到我的html文件中,问题就解决了。

相关问题