我有一个带有 x
和 y
集的 SVG 元素,但我也使用 transform="translate(a, b)"
将它转换为某个向量,这会更改它呈现的坐标,但显然不会更新其 x
和 y
属性。有没有办法获得实际坐标,在这种情况下是 x + a
和 y + b
,而不必直接解析 transform
属性中的值?
并不是说这是一个特定于 D3 的问题,但我的代码如下所示:
svg.selectAll(selector)
.attr("x", x)
.attr("y", y)
.attr("width", width)
.attr("height", height)
.attr("transform", `translate(${a}, ${b})`);
最佳答案
好吧,这不是真正的 D3 相关,而是纯 SVG/javascript:
我在这里使用这个我称之为“扁平化”的函数,基本上你想将矩阵重置为未转换的矩阵(矩阵(1 0 0 1 0 0))并使用它们的扁平值更新路径点:
flattenShape(item, matrix) {
let points = item.pathPoints;
let l = points.length;
for (let i = 0; i<l; i++) {
let cache = this.mainSVG.createSVGPoint();
cache.x = points[i].x;
cache.y = points[i].y;
cache = cache.matrixTransform(matrix);
points[i].x = cache.x;
points[i].y = cache.y;
}
item.d = this.constructPath(points);
item.transform = "matrix(1 0 0 1 0 0)";
};
item
- 您的 SVG 元素,matrix
- 您需要获取相关元素的实际 SVGMatrix
。我得到它使用:let matrix = YOUR_SVG_ELEMENT.transform.baseVal.consolidate().matrix;
所以我的方法可能太具体了,但总的来说:
关于javascript - 如何找到 SVG 元素的平移坐标?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48409500/