首页 > 解决方案 > 加载此标签时如何更改 svg 文本标签 XY?

问题描述

svg代码在这里

    function calculateXY(text, angle) {
        text.setAttribute('x',111.5 * Math.cos(angle) + 142.5);
        text.setAttribute('y',111.5 * Math.sin(angle) + 142.5);
    }
<svg width="285" height="285" class="pie-svg" >
        <g>
            <circle class="pie-1" r="111.5" cx="142.5" cy="142.5" stroke="#303840" stroke-dasharray="175 525" transform="rotate(0, 142.5,142.5)"></circle>
            <text class="pie-text-percent" onload="calculateXY(this, 45)" fill="#ffffff" transform="rotate(90, 142.5,142.5)">25%</text>
        </g>
    </svg>

我想在加载此标签时更改文本 xy,但它不起作用,我该怎么办?

标签: javascripthtmlcsssvg

解决方案


我已经改为text.setAttribute并且text.setAttributeNS它有点工作。但是,文本位于 svg 画布之外,您可以看到它,因为我已将 svg 溢出设置为可见。现在我需要了解您在哪里需要文本。

function calculateXY(text, angle) {
        text.setAttributeNS(null,'x',111.5 * Math.cos(angle) + 142.5);
        text.setAttributeNS(null,'y',111.5 * Math.sin(angle) + 142.5);
    }
svg{border:1px solid;overflow:visible}
circle{fill:none}
<svg width="285" height="285" class="pie-svg" >
        <g>
            <circle class="pie-1" r="111.5" cx="142.5" cy="142.5" stroke="#303840" stroke-dasharray="175 525" transform="rotate(0, 142.5,142.5)"></circle>
            <text class="pie-text-percent" onload="calculateXY(this, 45)" fill="#000" transform="rotate(90, 142.5,142.5)">25%</text>
        </g>
    </svg>


推荐阅读