【发布时间】:2021-06-03 18:32:04
【问题描述】:
有必要让文本尽可能多地填充 svg,就像 bacground-size: contain 一样。 svg 父级可以动态调整大小。文本总是单行。现在这样的解决方案是用js来做的,但是最好用svg本身来做。
const $svg = document.querySelector(`svg`);
const $text = $svg.querySelector('text');
const $input = document.querySelector('input');
$input.addEventListener('input', e => {
$text.textContent = e.target.value;
const box = $text.getBBox();
$svg.setAttribute('viewBox', `${box.x} ${box.y} ${box.width} ${box.height}`);
});
$input.dispatchEvent(new Event('input'))
svg {
border: 1px solid red;
height: 10em;
width: 100%;
}
<svg preserveAspectRatio="xMaxYMid meet">
<text alignment-baseline="baseline" dominant-baseline="middle" text-anchor="middle" fill="black"></text>
</svg>
<input type='text' value='Random single line text'>
【问题讨论】:
-
CSS Tricks 几年前对此进行了post,不确定从那以后有什么变化。它几乎是幻数或 Javascript,如果你想要动态,那么你需要 JS,为什么你不想使用 JS?
-
保罗在一年前回答了这个问题:stackoverflow.com/questions/34298838/svg-responsive-text
-
此答案不适用于很长或很短的文本。 CSS Tricks 使用魔法数字,这对我有用。
标签: svg