【问题标题】:How do I change the position of a circle svg element using the transform attribute?如何使用 transform 属性更改圆形 svg 元素的位置?
【发布时间】:2017-03-30 21:19:23
【问题描述】:

我目前正在 D3JS 中构建一个旭日形图,并尝试将圆圈附加到每个节点。您可以在此处查看当前项目:https://jsfiddle.net/mhxuo260/

我正在尝试将每个圆圈定位在其各自节点的右上角。目前它们只会定位在覆盖节点标签的中心。我一直在网上搜索以寻找线索,但还没有想出任何东西。任何建议将不胜感激。

d3.json("flare.json", function(error, root) {
if (error) throw error;

var g = svg.selectAll("g")
    .data(partition.nodes(root))
    .enter().append("g");

path = g.append("path")
    .attr("d", arc)
    .attr('stroke', 'white')
    .attr("fill", function(d) { return color((d.children ? d : d.parent).name); })
    .on("click", magnify)
    .each(stash);

var text = g.append("text")
    // .attr("x", function(d) { return d.x; })
    // .attr("dx", "6") // margin
    // .attr("dy", ".35em") // vertical-align
    .text(function(d) {
        return d.name;
    })
    .attr('font-size', function(d) {
        return '10px';
    })
    .attr("text-anchor", "middle")
    .attr("transform", function(d) {
        if (d.depth > 0) {
            return "translate(" + arc.centroid(d) + ")" +
                   "rotate(" + getStartAngle(d) + ")";
        } else {
            return null;
        }
    })
    .on("click", magnify);

var circle = g.append('circle')
    .attr('cx', function(d) { return d.x })
    .attr('cy', function(d) { return d.dy; })
    .attr('r', '10')
    .attr('fill', 'white')
    .attr('stroke', 'lightblue')
    .attr("transform", function(d) {
        console.log(arc.centroid(d))
        if (d.depth > 0) {
            return "translate(" + arc.centroid(d) + ")" +
                   "rotate(" + getStartAngle(d) + ")";
        } else {
            return null;
        }
    });

【问题讨论】:

    标签: javascript d3.js svg data-visualization


    【解决方案1】:

    您正在使用 ´´´arc.centroid´´´ 函数始终返回弧的 x,y 中点。该函数所做的只是:

    The midpoint is defined as (startAngle + endAngle) / 2 and (innerRadius + outerRadius) / 2
    

    您只需要根据您想要的位置使用这些值计算不同的位置。像这样使用转换(sudo 代码):

    .attr( "transform", function(d) {
            var x = (startAngle + endAngle) / 2;
            var y = (innerRadius + outerRadius) / 2;
    
            return "translate(" + x +"," + y + ")";
        });
    

    你不需要旋转你的圈子。

    (仅供参考:javascript 将通过用逗号连接每个数字将数组转换为字符串,这就是 arc.centroid 返回数组的原因)

    【讨论】:

      猜你喜欢
      • 2012-06-19
      • 1970-01-01
      • 2015-12-24
      • 1970-01-01
      • 2021-12-31
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多