Javascript 访问 svg transform translate 的 x/y 值

Javascript to access the x/y value of svg transform translate

目前是否有内置的javascript方法可以直接访问svgtransform =translate(x,y)xy?

例如下面的最小示例,我正在使用 svg 元素

document.querySelectorAll('circle').forEach(
    (a,i)=>{
       const transformString=  a.getAttribute('transform');
       const valX = parseFloat(transformString.match(/(\d+\.\d+)(?=\,)|(\d+)(?=\,)/gm))+10;
       a.setAttribute('transform',`${transformString.replace(/(\d+\.\d+)(?=\,)|(\d+)(?=\,)/gm,valX)}`)});
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>

<body>
<svg xmlns="http://www.w3.org/2000/svg" height="400" width="450">
  

<circle cx="0" cy="5" r="5" transform="translate(10,20)"></circle>
<circle cx="0" cy="5" r="5" transform="translate(25,30)"></circle>
<circle cx="0" cy="5" r="5" transform="translate(17.5,32.5)"></circle>
<circle cx="0" cy="5" r="5" transform="translate(10, 50)"></circle>

</svg>
</body>

</html>

并且此元素包含的现有圈子很少。

我想获取每个圆圈的 transform=translate(x,y) x 值并用自定义函数更改它。

我目前正在这样做,如果存在内置(vanilla 和 /d3)方法可以直接访问 x 或 [,我想避免编写 regex =18=] 共 transform=translate

document.querySelectorAll('circle').forEach(
    (a,i)=>{
       const transformString=  a.getAttribute('transform');
       //grab the X value with regex and change as desired
       const valX = parseFloat(transformString.match(/(\d+\.\d+)(?=\,)|(\d+)(?=\,)/gm))+10;
       //replace existing X with new X
       a.setAttribute('transform',`${transformString.replace(/(\d+\.\d+)(?=\,)|(\d+)(?=\,)/gm,valX)}`)});

d3相当于

d3.selectAll('circle')
    .attr('transform', function (d,i) {
        const transformString= this.getAttribute('transform');
        const valX = parseFloat(transformString.match(/(\d+\.\d+)(?=\,)|(\d+)(?=\,)/gm))+10;
        return `${transformString.replace(/(\d+\.\d+)(?=\,)|(\d+)(?=\,)/gm,valX)}`  
    });
document.querySelectorAll('circle').forEach(
    circle => {
       const additionalTransform = circle.ownerSVGElement.createSVGTransform();
       additionalTransform.setTranslate(10, 0);
       circle.transform.baseVal.appendItem(additionalTransform);
       // When doing this multiple times, `translate()`s might be piling up,
       // like transform="translate(10, 0) translate(10, 0) translate(10, 0)".
       // Consolidate them into a single matrix transformation.
       circle.transform.baseVal.consolidate();
    }
);