首页 > 解决方案 > 使用 Group BBOX 查找 SVG 元素的新坐标

问题描述

如何获取图像元素的新大小和坐标属性,以便父组容器 BBOX 应该更改为新的目标值。

这是我的 SVG:

<svg width="500"height ="500" xmlns="http://www.w3.org/2000/svg">
  <g id="my_grp">
    <image width="350" height="150" transform="translate(100 100) rotate(35 175 75)" href="https://via.placeholder.com/350x150"></image>
  </g>
</svg>

从那个例子中,我得到了“my_grp”的初始边界框,使用document.getElementById('my_grp').getBBox()的是:

[object SVGRect] {
  height: 323.62457275390625,
  width: 372.73968505859375,
  x: 88.63015747070312,
  y: 13.18772029876709
}

我想将 my_grp 框调整 30% 并将其移动到 (30, 40) 坐标。如何更改图像属性以实现它?

您可以查看https://jsfiddle.net/ybjL0zmt/

谢谢!

标签: svgcoordinates

解决方案


您可以获得SVGMatrix接口的帮助来计算必要的转换。从单位矩阵开始,然后移动坐标系以将组内容绘制到:

const group = document.querySelector('#my_grp');
const bbox = group.getBBox();
// initialize an identity matrix
const matrix = document.querySelector('svg').createSVGMatrix();

const {a, b, c, d, e, f} = matrix
    .translate(30, 40)
    .scale(0.7)
    .translate(-bbox.x, -bbox.y);

const transform = 'matrix(' + [a, b, c, d, e, f].join(',') + ')';
group.setAttribute('transform', transform);
<svg width="500"height ="500" xmlns="http://www.w3.org/2000/svg">
  <path d="M30 150V40H200" style="fill:none;stroke:black;stroke-dasharray:5 5" />
  <g id="my_grp">
    <image width="350" height="150" transform="translate(100 100) rotate(35 175 75)" href="https://via.placeholder.com/350x150"></image>
  </g>
</svg>


推荐阅读