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

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

本文关键字:元素 svg 位置 transform 何使用 属性      更新时间:2023-09-26

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

您正在使用" ' ' '圆弧。质心' ' '函数,它总是返回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的原因。质心在这里返回一个数组)