首页 > 解决方案 > 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);

标签: javascripthtmlsvg

解决方案


.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>


推荐阅读