d3词云 - 单词出界

时间:2014-11-25 20:36:33

标签: javascript d3.js

我正在使用d3词云(https://github.com/jasondavies/d3-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");
    });
}

enter image description here

2 个答案:

答案 0 :(得分:1)

设置text-anchor属性以启动并在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");
});

}

答案 1 :(得分:0)

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