gpt4 book ai didi

javascript - 旋转路径后计算 SVG 尺寸

转载 作者:行者123 更新时间:2023-12-03 01:29:58 29 4
gpt4 key购买 nike

问题是如何使用数学从 START SVG 维度(不带旋转)和 END SVG 维度(带旋转)获取 >开始 SVG 信息。基本上,要从 START SVGEND SVG,我需要执行 -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>

最佳答案

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

关于javascript - 旋转路径后计算 SVG 尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51346869/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com