javascript - SVG:当 y 属性为 200 时,为什么 getBoundingClientRect 返回 190?
问题描述
下面的代码将 textBox1 放置在 200 的 y 位置,但 getBoundingClientRect 返回值 190。
为什么?
https://codepen.io/anon/pen/REKayR?editors=1011
<svg id="rootBox" width="500" height="800" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<rect x="0%" y="0%" width="100%" height="100%" fill="beige" />
<svg id="textBox1" x="0%" y="200" width="100%" height="25%">
<rect class="background" x="0%" y="0%" width="100%" height="100%" fill="gray" fill-opacity="0.5" />
<text class="textGroup" x="0" y="0"><tspan x="50%" dy="-0.25em" text-anchor="middle">tspan line 0</tspan><tspan x="50%" dy="1.5em" text-anchor="middle">tspan line 1</tspan><tspan x="50%" dy="1.5em" text-anchor="middle">tspan line 2</tspan></text>
</svg>
</svg>
var textBox = $("#textBox1");
var textBBox = textBox[0].getBoundingClientRect();
console.log("The y-pos is: " + textBBox.y);
解决方案
.getBoundingClientRect()
是通用Element
接口的一部分,并计算与屏幕视口相关的矩形。SVG 提供了一些更具体的方法:
SVGGraphicsElement.getBBox()
计算绘制元素的局部坐标系中的边界框。SVGGraphicsElement.getCTM()
计算局部坐标系和最近的SVG 视口(<svg>
例如元素)之间的变换矩阵。SVGGraphicsElement.getScreenCTM()
计算局部坐标系和屏幕视口之间的变换矩阵。
此外,该DOMMatrix
接口有一个.inverse()
方法,因此您可以轻松计算相反方向的位置。(例如,如果您使用 的结果转换鼠标事件 screenx/screenY 位置element.getScreenCTM().inverse()
,您将获得相对于该元素的鼠标位置。)
有点尴尬的是你必须构造一个SVGPoint
对象,这只能通过元素SVGSVGElement.createSVGPoint()
上的方法来实现,才能有一些东西可以应用你的矩阵。<svg>
至于您的问题,请考虑内部 rect 的三个坐标系的不同返回值<svg>
:
var textBox = document.querySelector('#textBox1 rect');
var svg = document.querySelector('#rootBox');
var point = svg.createSVGPoint();
var local = textBox.getBBox();
point.x = local.x, point.y = local.y;
console.log("local: ", local.x, local.y);
var nearest = textBox.getCTM();
var point2 = point.matrixTransform(nearest);
console.log("nearest viewport: ", point2.x, point2.y);
var screen = textBox.getScreenCTM();
var point3 = point.matrixTransform(screen);
console.log("screen viewport: ", point3.x, point3.y);
<svg id="rootBox" width="500" height="800" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<rect x="0%" y="0%" width="100%" height="100%" fill="beige" />
<svg id="textBox1" x="0%" y="200" width="100%" height="25%">
<rect class="background" x="0%" y="0%" width="100%" height="100%" fill="gray" fill-opacity="0.5" />
<text class="textGroup" x="0" y="0"><tspan x="50%" dy="-0.25em" text-anchor="middle">tspan line 0</tspan><tspan x="50%" dy="1.5em" text-anchor="middle">tspan line 1</tspan><tspan x="50%" dy="1.5em" text-anchor="middle">tspan line 2</tspan></text>
</svg>
</svg>
推荐阅读
- bash - 用 var=$?; 测试命令的存储退出状态 [[ $var ]] 始终为真,无论是 0 还是 1
- python - Tensorflow 2.0 Keras 中过激激活值的正则化
- php - Laravel-echo 无法收听私人和在线频道
- python - 如何在 Django 中为单个行/对象存储多个图像,以便我可以轻松地检索它们或执行其他查询操作?
- c# - 如何将循环转换为 Linq
- c++ - C++中输入char变量后程序的执行结束
- android - 单击 LibGdx 更改 ImageButton 的纹理
- c# - .NET Core 3 和 System.Windows.Shapes.Rectangle 和 XamlReader.Parse
- php - PHP数组 - 将数字(值)附加到每个元素的字符串(键)
- html - 宽度减小时如何增加高度?