【问题标题】:How to calculate the coordinate of a SVG object after rotation and scaling?如何计算旋转和缩放后的SVG对象的坐标?
【发布时间】:2016-04-26 10:57:04
【问题描述】:

我想知道 SVG 对象在旋转和缩放之后的坐标(即 如果我们知道起始 x、y 坐标和高度、宽度,则结束 x 和 y 坐标) .

有没有办法计算旋转后 SVG 对象的结束坐标?

如果有人知道请帮我解决这个问题。

【问题讨论】:

  • 对每个坐标应用变换矩阵
  • 你知道旋转和平移后的起始x和y坐标吗?
  • 如果你有任何小提琴,那么它对我理解问题更有帮助

标签: css svg coordinates coordinate-systems


【解决方案1】:

BBox 方法有助于在应用形状或对象之后或之前获取起点和终点。

You can select the object using d3 or jquery
        if you are using d3 the select in this way 
                    var rect = d3.select(selecteObject);
        if jquery then 
                   var rect = $(selecteObject);
                   var newx = rect.node().getBBox().x;
                   var newy = rect.node().getBBox().y;
                   var neww = rect.node().getBBox().width;
                   var newh = rect.node().getBBox().height;
                   var endCodinatex = newx + neww;
                   var endCodinatY = newy + newh;

【讨论】:

    【解决方案2】:

    正如 Robert Longson 所说,您可以将变换矩阵应用于每个坐标。

    您可以使用 SVGLocatable 接口中的 getCTM() 方法获取转换矩阵。

    http://www.w3.org/TR/SVG/types.html#InterfaceSVGLocatable

    例如下面的sn-p将变换矩阵应用于rect元素的(x,y)坐标。

    var pointBefore = document.getElementById("pointBefore");
    var pointAfter = document.getElementById("pointAfter");
    var svg = document.getElementById("svg");
    var rect = document.getElementById("rect");
    var ctm = rect.getCTM();
    var p = svg.createSVGPoint();
    p.x = rect.getAttribute("x");
    p.y = rect.getAttribute("y");
    pointBefore.textContent = p.x + ", " + p.y;
    p = p.matrixTransform(ctm);
    pointAfter.textContent = p.x + ", " + p.y;
    <svg id="svg" width="200" height="200" style="border: 1px solid black;">
        <rect id="rect" x="25" y="25" width="50" height="50" transform=" scale(2) rotate(15,50,50)"/>
    </svg>
    <p>point (before transform): <tspan id="pointBefore"></tspan></p>
    <p>point (after transform): <tspan id="pointAfter"></tspan></p>

    【讨论】:

      猜你喜欢
      • 2012-10-17
      • 1970-01-01
      • 2018-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多