d3.js svg 未调整大小

d3.js svg not resizing

我正在尝试将我自己的数据源与 existing bl.ocks demonstration of a word cloud. Here's what I've done 一起使用,如您所见,text/block 非常小。我正在尝试调整 svg 和文字云元素的大小以占据屏幕的整个宽度,但到目前为止我没有通过调整这些元素的大小获得所需的响应:

 d3.layout.cloud().size([2000, 2000])
            .words(frequency_list)
            .rotate(0)
            .fontSize(function(d) { return 3*d.size; })
            .on("end", draw)
            .start();

    function draw(words) {
        d3.select("body").append("svg")
                .attr("width", 4000)
                .attr("height",2000)
                .attr("class", "graph-svg-component")
                .attr("class", "wordcloud")
                .append("g")
                // without the transform, words words would get cutoff to the left and top, they would
                // appear outside of the SVG area
                .attr("transform", "translate(320,200)")
                .selectAll("text")
                .data(words)
                .enter().append("text")
                .style("font-size", function(d) { return d.size + "px"; })
                .style("fill", function(d, i) { return color(i); })
                .attr("transform", function(d) {
                    return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
                })
                .text(function(d) { return d.text; });
    }

如何让词云扩展到我的屏幕的整个宽度?感谢您的任何建议。

svg当您创建 svg 时,宽度被分配给 svg 作为属性,而不是样式。

因此,当您调整容器大小时,需要通知 svg 宽度属性。

你可以做的是创建这样的东西:

$(window).on('resize', resizeSvg);

    function resizeSvg() {
        svg.attr('width', $('#svg-container').width());
    }

这是我项目中的部分代码,你应该模仿它。

这里需要增加位置偏移:

.attr("transform", "translate(320,200)")

类似于:

.attr("transform", "translate(500, 500)")

这与云的大小有关

但是请注意,如果您想将云放入 window,则必须考虑 window 的尺寸并按照@的建议更新更改范围华振阳