【问题标题】:Fit text into svg without using js在不使用 js 的情况下将文本放入 svg
【发布时间】: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


【解决方案1】:

你不能只使用父母div吗?向文本添加无环绕属性(word-breakflex-wrap 用于 flex 容器),这会将 div 拉伸到全文宽度。然后在div 中创建svg width: 100%

【讨论】:

  • 拉伸 div 不改变字体大小。
  • 不,它没有,我在这里得到了你想要的错误。您不只是希望文本填充 svg 吗?所以调整 svg 的大小会有所帮助。或者您的意思是您希望文本调整大小,并且用户控制 svg 的大小?
  • 文本应尽可能多地填充 svg。
猜你喜欢
  • 2022-09-27
  • 2021-12-25
  • 2019-07-16
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多