Javascript d3单词云-单词超出范围

Javascript d3单词云-单词超出范围,javascript,d3.js,Javascript,D3.js,我使用的是d3 word cloud(),我似乎无法将这些单词保持在限定范围内。大约每3或4次加载,它就会删除一个单词 d3.layout.cloud() .size([800, 300]) .words(words) .overflow(true) .rotate(0) .padding(6) .fontSize(function(d) { return d.size; }) .on

我使用的是d3 word cloud(),我似乎无法将这些单词保持在限定范围内。大约每3或4次加载,它就会删除一个单词

d3.layout.cloud()
        .size([800, 300])
        .words(words)
        .overflow(true)
        .rotate(0)
        .padding(6)
        .fontSize(function(d) { return d.size; })
        .on("end", draw)
        .start();

function draw(words) {
    d3.select("#d3").append("svg")
            .attr("width", 800)
            .attr("height", 300)
            .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(370,155)")
            .selectAll("text")
            .data(words)
            .enter()
            .append("text")
            .style("-webkit-text-stroke-width", "1px")
            .style("-webkit-text-stroke-color", "black")
            .style("font-size", function(d) { return d.size + "px"; })
            .style("fill", function(d, i) { return color(i); })
            .attr("text-anchor", "middle")
            .attr("transform", function(d) {
                return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
            })
            .text(function(d) { return d.text; })
            .on("click", function (d, i){
             window.open(d.url, "_self");
    });
}

您必须减小单词字体大小,以确保单词适合svg或增加svg的大小。

将文本锚属性设置为开始,并在translate方法中对d.x值使用Math.abs()将有所帮助

将留下以下内容作为绘图功能:

function draw(words) {
d3.select("#d3").append("svg")
        .attr("width", 800)
        .attr("height", 300)
        .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(370,155)")
        .selectAll("text")
        .data(words)
        .enter()
        .append("text")
        .style("-webkit-text-stroke-width", "1px")
        .style("-webkit-text-stroke-color", "black")
        .style("font-size", function(d) { return d.size + "px"; })
        .style("fill", function(d, i) { return color(i); })
        .attr("text-anchor", "start")
        .attr("transform", function(d) {
            return "translate(" + [Math.abs(d.x), d.y] + ")rotate(" + d.rotate + ")";
        })
        .text(function(d) { return d.text; })
        .on("click", function (d, i){
         window.open(d.url, "_self");
});

}

此实现没有任何强制要求,即所有内容都保持在提供的大小内。你必须使画布变大,字体变小或减少字数。