【问题标题】:Text Inside SVG Circle in D3 Doesn't ShowD3 中 SVG 圆圈内的文本不显示
【发布时间】:2017-07-31 08:53:17
【问题描述】:

我正在尝试在SVG 圆圈内附加文本,例如我的D3 地图中的 this 示例。我在 SO 上看到了很多类似的问题 - 我用它们编写了下面的代码,但不明白为什么它根本没有出现。

d3.json("https://raw.githubusercontent.com/d3/d3.github.com/master/world-110m.v1.json", function (error, topo) {
            if (error) throw error;

            gBackground.append("g")
                .attr("id", "country")
                .selectAll("path")
                .data(topojson.feature(topo, topo.objects.countries).features)
                .enter().append("path")
                .attr("d", path);


            gBackground.append("path")
                .datum(topojson.mesh(topo, topo.objects.countries, function (a, b) { return a !== b; }))
                .attr("id", "country-borders")
                .attr("d", path);


            console.log("Background Drawn");

           var point = gPoints.selectAll("circle")
                .data(pointsData)     
                .enter()            
                .append("circle")    
                .attr("cx", function (d) { return d.location[0]; })
                .attr("cy", function (d) { return d.location[1]; })
                .attr("r", 10)
                //Other attributes and mouseovers, etc


           var texts = gPoints.selectAll("text")
               .data(pointsData)
               .enter()
               .append("text")
               .text(function (d) { return d.performance; });

            console.log("Points Drawn");

        });

【问题讨论】:

    标签: javascript d3.js svg text


    【解决方案1】:

    text没有出现的原因是:你没有指定任何需要出现的位置。

    对于圈子,您提供了 cxcy,但没有提供文本。

    更好的方法是创建一个这样的组:

    var elem = gPoints.selectAll("g .myCircleText").data(pointsData)
    /*Create and place the "blocks" containing the circle and the text */  
    var elemEnter = elem.enter()
        .append("g")
        .classed("myCircleText", true) //add a class to the group
        .attr("transform", function(d){return "translate("+d.location[0]+","+ d.location[1]+")"})
    

    如上所示给组一个翻译(这样你就不需要给一个 cx 和 cy 组被翻译到所需的点)。

    现在像这样在组内画圈:

    /*Create the circle for each block */
    var circle = elemEnter.append("circle")
        .attr("r", 10 )
        .attr("stroke","black")
        .attr("fill", "white")
    

    现在在组内制作文本

    /* Create the text for each block */
    elemEnter.append("text")
        .attr("dx", function(d){return -20})//so that it comes 20 pixel from center.
        .text(function(d){return d.performance})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      • 2016-06-20
      相关资源
      最近更新 更多