我正在研究 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 的比例?
I tried e.getCTM()
and e.getScreen()
。该矩阵不包含尺度信息。
请给我一些建议。
另一个SO答案 https://stackoverflow.com/a/26893663/5218951展示如何使用获取元素相对于文档的比例element.getBoundingClientRect().width / element.offsetWidth
。但是,那svg
元素不具有offsetWidth
财产。因此,一种解决方案是临时在前面添加一个“offsetWidth-able”元素svg
元素,例如Adiv
,读取这个临时助手上的比率,然后将其删除。如果插入的元素将通过 CSS 应用意外的缩放变换(如代码片段所示),则该插入的元素应具有以下样式:transform: scale(1);
直接应用到它上面。
Update:当包含比例的 CSS 变换直接应用于svg
元素本身。在这种情况下,需要解析样式,可以使用以下命令来完成getComputedStyle
and getPropertyValue
,并从返回的矩阵字符串中提取比例值。然后需要乘以前置的相对比例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>
当您运行上面的代码片段时,您可能需要在代码片段窗口中向下滚动或单击“完整页面”才能查看结果。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)