【问题标题】:svg : find x,y coordinates of rect verticessvg : 查找矩形顶点的 x,y 坐标
【发布时间】:2019-04-10 05:58:29
【问题描述】:

我在网页上有各种 svg rects,在该网页上应用了以下形式的转换:

    transform="translate(418 258) rotate(-45.2033 15 18) scale(2.5 2.5)"

我需要在应用变换后获取每个矩形的 4 个顶点的 x,y 坐标。

这是一个代码示例:

<g transform="translate(418 258) rotate(-45.25 15 18) scale(2.5 2.5)">
  <rect id="box" x="0" y="0" width="31" height="37" style="fill:none;stroke:rgb(102, 102, 102);stroke-width:1.5px;">
  </rect>
</g>

我在纯js中尝试过以下公式:

x' = x * cos(angle) + y * sin(angle)
y' = -x * sin(angle) + y * cos(angle)

但结果与各种浏览器显示的svg略有不同。

我想这可以使用 js/svg 原语来完成,但我不知道如何,也没有找到任何代码示例。也许在转换后将矩形更改为路径会起作用...

最后但同样重要的是,我使用的是 jquery 而不是 d3。

提前致谢。

【问题讨论】:

  • 可以分享svg标签吗?他们有ids 或classes 吗?
  • 我刚刚添加了我的 js/svg 代码示例。
  • 你能解释一下你需要坐标吗?可能有其他方法。
  • 我有一个检测线段交叉点的函数,我想用它来检测转换后的矩形和其他 svg 路径之间可能的交叉点。这就是为什么将转换后的矩形更改为路径可能是一种解决方案......
  • 使用getCTM() 方法可能会对您有所帮助。请查看此问题的已接受答案:How get tight bounding box of an SVG Text Element

标签: javascript svg rect vertices


【解决方案1】:

您可以读取 transform 属性并将其转换为矩阵。 然后对于矩形的四个角中的每一个,您都可以使用该矩阵来计算转换后的角位置。

请看下面的演示。

此演示假定有一个元素为id"box",并且您关心的转换只是父&lt;g&gt; 元素上的转换。如果您的情况比这更复杂,那么您将需要对这段代码做更多的工作。

// Get a reference to the "box" rect element
var box = document.getElementById("box");
// Get its x, y, width and height
var bx = box.x.baseVal.value;
var by = box.y.baseVal.value;
var bw = box.width.baseVal.value;
var bh = box.height.baseVal.value;

// Get the box's parent element (the <g>)
var parentGroup = box.parentNode;
// Read the transform attribute and convert it to a transform matrix object
var transformMatrix = parentGroup.transform.baseVal.consolidate().matrix;

// For each of the rectangle's four corners, use the transform matrix to calculate its new coordinates
console.log("point 1 = ", doPoint(bx, by));
console.log("point 2 = ", doPoint(bx + bw, by));
console.log("point 3 = ", doPoint(bx + bw, by + bh));
console.log("point 4 = ", doPoint(bx, by + bh));



function doPoint(x, y)
{
  // We need a reference to the <svg> element for the next step
  var svg = box.ownerSVGElement;
  // Create an SVGPoint object with the correct x and y values
  var pt = svg.createSVGPoint();
  pt.x = x;
  pt.y = y;
  // Use the "matrixTransform()" method on SVGPoint to apply the transform matrix to the coordinate values
  pt = pt.matrixTransform(transformMatrix);
  // Return the updated x and y values
  return {x: pt.x, y: pt.y};
}
<svg>
  <g transform="translate(418 258) rotate(-45.25 15 18) scale(2.5 2.5)">
    <rect id="box" x="0" y="0" width="31" height="37" style="fill:none;stroke:rgb(102, 102, 102);stroke-width:1.5px;">
    </rect>
  </g>
</svg>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 2013-02-01
    • 2015-11-20
    • 2016-08-28
    • 1970-01-01
    相关资源
    最近更新 更多