以自然方式附加文本对象D3.js

时间:2016-04-05 00:31:32

标签: javascript d3.js svg

我是D3的新手。我想在屏幕上显示一个句子,我有一个数组中的单词,当我运行代码时所有单词都重叠,我希望它们像普通文本一样以自然的方式显示。

function post(path, params, method) {
    method = method || "post"; // Set method to post by default if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    form.submit();
}

1 个答案:

答案 0 :(得分:2)

一种简单的方法是在单个文本元素中使用tspan元素。

var margin = {top: 20, right: 20, bottom: 30, left: 20},
        width = 960 - margin.left - margin.right,
        height = 500 - margin.top - margin.bottom;


var svgContainer = d3.select("body").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 + ")");


var text = svgContainer.append("text");

var cars=["this","is","a","normal","sentence"];

var text = text.selectAll("tspan")
                        .data(cars)
                        .enter()
                        .append("tspan");

//Add SVG Text Element Attributes
var textLabels = text

                 .text( function (d) { return d + ' '; })
                 .attr("font-family", "sans-serif")
                 .attr("font-size", "20px")
                 .attr("fill", "red");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>