我将HTML文本和包含文本的SVG文档作为外部对象包含在内。我希望HTML文本的大小与SVG文档中的文本大小保持一致。
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>getComputedStyle</title>
</head>
<body>
<h3 id="headerId">Header</h3>
<object onload="svgLoaded()" id="sampleSVG" data="sample.svg"
type="image/svg+xml" width="80%"></object>
<script>
let element = document.getElementById("headerId");
console.log(window.getComputedStyle(element)
.getPropertyValue("font-size"));
console.log(element.getBoundingClientRect().height);
var svgLoaded = function () {
svgObject = document.getElementById("sampleSVG");
var svgObjectIntern = svgObject.contentDocument;
var textElement =
svgObjectIntern.getElementsByTagName('text');
for (var i = 0; i < textElement.length; i++) {
let selectedText = textElement[i];
console.log(window
.getComputedStyle(selectedText)
.getPropertyValue("font-size"));
console.log(selectedText.getBoundingClientRect().height);
}
}
</script>
</body>
</html>修改SVG文档中的文本大小很好(我使用的是d3.js),但作为第一步,我需要用户看到的文本大小。如果我调整浏览器窗口的大小或更改SVG对象的“宽度”,HTML文本大小保持不变,而SVG中的文本大小按比例变化。
为了测量用户看到的文本大小,我尝试了"getComputedStyle“和"getBoundingClientRect”。SVG工作得很好,但是getComputedStyle总是告诉我getBoundingClientRect文档中定义的文本大小独立于任何缩放比例。
原则上,我对"getBoundingClientRect“没意见。唯一的缺点是,这总是需要在SVG中有一个水平文本元素,但并不是我的所有SVG文档都是这样的。当然,我可能会引入一个透明的水平样本文本。
我有种感觉,那不是很聪明。也许有更好的解决方案。
发布于 2019-03-16 22:16:53
您可以获得transform matrix,它将定义文本的本地坐标系转换为呈现SVG的视区(在本例中为<object>标记)。
虽然将SVG作为一个整体进行转换以适应<object>元素的大小是一个简单的缩放(在大多数情况下是一致的),但在SVG内部可能发生了其他转换:它可能缩放不均匀、旋转或倾斜。这一切都会反映在矩阵的内容中,这使得矩阵的解释变得复杂。下面的代码示例仅处理最简单的情况,并假定ctm.d属性的值是应用于字体大小的均匀缩放的表示形式。
阅读有关矩阵here的数学解释的更多信息。
var svgLoaded = function () {
svgObject = document.getElementById("sampleSVG");
var svgObjectIntern = svgObject.contentDocument;
var textElement = svgObjectIntern.getElementsByTagName('text');
for (var i = 0; i < textElement.length; i++) {
var selectedText = textElement[i];
var fontsize = window
.getComputedStyle(selectedText)
.getPropertyValue("font-size"));
var ctm = selectedText.getScreenCTM();
console.log(parseFloat(fontsize) * ctm.d);
}https://stackoverflow.com/questions/55195261
复制相似问题