svg - 使用 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/。
谢谢!
解决方案
您可以获得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>
推荐阅读
- python - Ray on_train_result 回调获取 episode_id
- java - 在最后一行代码的主要方法中,我有一个目录可以从我的桌面运行 maze.txt
- r - 通过匹配列中的值来合并R中不同长度的数据集?
- ruby-on-rails - Sequel Connection 池中的多个连接
- laravel - Public_path 的 Laravel 错误不起作用
- mysql - MySQL New Column at SELECT 添加,但值没有增加,存储过程
- javascript - 使用引导下拉子菜单
- wcf - WCF Datacontract for XML 比单层更深
- python - Python洪水填充不返回
- python - 在 Python 中将图像导入为“imageio.core.util.Image”类型的 RGB 像素