旋转路径后计算SVG尺寸



问题是如何使用数学从START SVG维度(不旋转(到END SVG维度(旋转(,并且只知道START SVG信息。基本上,为了从START SVGEND SVG,我需要执行-115.609degrotation

以下是我对的看法

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

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>

以下是如何在浏览器中使用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>

最新更新