【问题标题】:Calculate SVG Dimensions after rotating a path旋转路径后计算 SVG 尺寸
【发布时间】:2018-12-23 02:50:40
【问题描述】:

问题是如何使用数学从START SVG 维度(无旋转)和END SVG 维度(有旋转)中获取,并且仅通过了解START SVG 信息。 基本上要从START SVGEND SVG 我需要执行rotation-115.609deg

这是我的想法

从路径中检索每个点,然后对每个点应用旋转

START SVG

<svg xmlns="http://www.w3.org/2000/svg" width="92" height="63" viewBox="0 0 92 63" fill="none">
    <path d="M90.6668 0H0L49.9325 61.7586L90.6668 0Z" fill="#6F7800" />
</svg>

END SVG(这就是我想要实现的,但使用数学),这是 100% 准确的

<svg xmlns="http://www.w3.org/2000/svg" width="75" height="83" viewBox="0 0 75 83" fill="none">
    <path d="M90.6668 0H0L49.9325 61.7586L90.6668 0Z" transform="translate(40.1452 82.6093) rotate(-115.609)" fill="#6F7800" />
</svg>

【问题讨论】:

  • 有什么意义?您想在这里实现什么目标?
  • 我正在尝试从第一个 svg 旋转路径后找到公式
  • 第一个 svg 和第二个 svg 之间的数学运算是什么
  • 你为什么在乎?您想在这里解决什么问题?
  • 我的问题很简单,我想将路径旋转-115.609deg并调整路径的位置和svg的高度/宽度。第二个 svg 只是为了展示我想要实现的目标

标签: javascript svg matrix css-transforms


【解决方案1】:

这是在浏览器中使用 JS 的方法。

请注意,这适用于 Firefox,但不适用于 Chrome(可能也不适用于 Safari),因为 Chrome 计算转换内容的边界框的方式。

function rotateAndAdjust(elem, angle)
{
  // Rotate the element by the angle
  elem.setAttribute("transform", "rotate("+angle+")");
  // Call getBBox to get the updated bounding box
  var bbox = elem.parentElement.getBBox();
  // Use the BBox x and y to move the element back into the viewport
  elem.setAttribute("transform", "translate(" + (-bbox.x) + "," + (-bbox.y)+") rotate(" + angle + ")");
  // Convert the new width and height to integers
  var w = Math.ceil(bbox.width);
  var h = Math.ceil(bbox.height);
  // Update the viewBox
  elem.ownerSVGElement.setAttribute("viewBox", "0 0 " + w + " " + h);
  // Update the SVG width and height  
  elem.ownerSVGElement.setAttribute("width", w);
  elem.ownerSVGElement.setAttribute("height", h);
}


rotateAndAdjust( document.querySelector("path"), -115.609 );
svg {
  background: linen;
}
<svg xmlns="http://www.w3.org/2000/svg" width="92" height="63" viewBox="0 0 92 63" fill="none">
<g>
    <path d="M90.6668 0H0L49.9325 61.7586L90.6668 0Z" fill="#6F7800" />
</g>
</svg>

【讨论】:

  • 只是一个澄清。它适用于 Chrome。你只是没有得到最紧密的边界框。
猜你喜欢
  • 2014-02-19
  • 2011-10-25
  • 1970-01-01
  • 2010-11-11
  • 2015-09-13
  • 2015-02-26
  • 2019-04-15
  • 2016-01-16
  • 1970-01-01
相关资源
最近更新 更多