繁体   English   中英

如何使用transform属性更改圆形svg元素的位置?

[英]How do I change the position of a circle svg element using the transform attribute?

我目前正在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;
        }
    });

您正在使用“´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返回数组的原因)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM