gpt4 book ai didi

javascript - 如何获得 svgElement 的比例?

转载 作者:行者123 更新时间:2023-11-27 23:31:25 24 4
gpt4 key购买 nike

我正在研究 svg。

<div id="wrap"  style="transform: scale(2); width:300;height:300;">
<svg id="real" style="border:red 10px solid;" >
<rect/>
</svg>
</div>
var e = document.getElementById("real");
//an api to get scale from e directly ??

我的问题是,如何获取这个 svgElement 的比例?

我尝试了 e.getCTM()e.getScreen()。矩阵不包含尺度信息。

请给我一些建议。

最佳答案

Another SO answer展示了如何使用 element.getBoundingClientRect().width/element.offsetWidth 获取元素相对于文档的比例。但是,svg 元素没有 offsetWidth 属性。因此,一种解决方案是临时在 svg 元素前添加一个“offsetWidth-able”元素,例如一个div,读取这个临时 helper 上的比例,然后删除它。如果插入的元素将通过 CSS 对其应用意外的比例变换(如代码片段所示),则此插入的元素应具有 transform: scale(1); 的样式直接应用于它。

更新:当包含比例的 CSS 转换直接应用于 svg 元素本身时,会出现更复杂的情况。在这种情况下,需要对样式进行解析,这可以使用 getComputedStylegetPropertyValue 来完成,并从返回的矩阵字符串中提取比例值。然后需要将其乘以前置 div 的相对比例。

进一步更新:此解决方案目前似乎无法在 Safari 中运行,因为浏览器无法识别 insertAdjacentHTML,尽管我能找到的文档说明了这一点应该。 (这是 Safari 的错误还是我遗漏了什么?)但是,该解决方案在 Firefox 和 Chrome 中确实有效。

var e = document.getElementById("real");
var computedTransform = window.getComputedStyle(e).getPropertyValue("transform");
if (computedTransform === "none") {
eDirScale = 1;
} else {
var matrix = computedTransform.match(/matrix\(([^\)]*)\)/)[1].split(/, *| +/);
var scaleX = Math.sqrt(matrix[0] * matrix[0] + matrix[1] * matrix[1]);
var scaleY = Math.sqrt(matrix[2] * matrix[2] + matrix[3] * matrix[3]);
if (scaleX !== scaleY) throw "non-uniform scaling";
eDirScale = scaleX;
}
var eRelScale = e.getBoundingClientRect().width / e.offsetWidth;
e.insertAdjacentHTML('beforebegin', '<div id="temporaryPrepended" style="transform: scale(1)"></div>');
var prepended = document.getElementById("temporaryPrepended");
var pRelScale = prepended.getBoundingClientRect().width / prepended.offsetWidth;
prepended.parentNode.removeChild(prepended);
var scale = pRelScale * eDirScale;

document.write("<p>scale directly on 'svg': " + eDirScale + "</p>");
document.write("<p>scale on 'svg' relative to document: " + eRelScale + ", i.e. doesn't work in e.g. Firefox and, while it might work in Chrome (in Feb 2016), apparently won't in the near future</p>");
document.write("<p>scale on prepended 'div' relative to document: " + pRelScale + "</p>");
document.write("<p>total scale on 'svg' relative to document: " + scale + "</p>");
div {
transform: scale(4);
}
<div id="wrap"  style="transform: scale(2); width:300;height:300;">
<svg id="real" style="transform: translate(10px, 10px) scale(1.5); border:red 10px solid; opacity: 0.3;" >
<rect/>
</svg>
</div>

当您运行上面的代码片段时,您可能必须在片段窗口中向下滚动或单击“整页”才能查看结果。

关于javascript - 如何获得 svgElement 的比例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35545593/

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