javascript - SVG 文本元素的就绪事件

标签 javascript html svg dom-events

有什么方法可以知道SVG文本元素已经完成了页面上的所有渲染步骤吗?

例如,当将文本设置为不同的字体系列时,文本首先更改其大小,然后将其外观更改为新字体, 然后它再次改变大小(甚至发生几次),然后变得更锐利。

这些步骤在不同的浏览器中有所不同,并且取决于许多进程,例如字体后备和加载新的字体文件。

如果不知道,当文本元素完成准备后,就不可能获得文本元素的实际尺寸(宽度和高度),因为浏览器可以随时调整它们以获得更好的外观或其他东西别的。如果没有此事件,则无法在基于 SVG 的在线编辑器中对文本进行正常处理。

我必须设置一个很长的计时器,希望在触发它时文本已经准备好。但是,当文本元素较多时,如果我们需要依次设置它们的参数,并在下一步之前获得之前的文本大小结果,那么这个时间就太长了。

最佳答案

您的问题归结为能够知道特定 FontFace 何时加载。

为此,您可以使用 FontFace API

对于在 CSS 中声明并在页面加载时直接使用的字体,文档公开了 fonts.ready属性是一个 Promise,当 DOMContentLoaded 中使用的所有字体都准备好时,该 Promise 将得到解析:

// only for demo (avoids cache)
const style = document.createElement('style');
style.textContent = `@font-face {
  font-family: 'Shadows Into Light';
  src: url("https://fonts.gstatic.com/s/shadowsintolight/v7/UqyNK9UOIntux_czAvDQx_ZcHqZXBNQzdcD55TecYQ.woff2?t=${ Math.random()}") format('woff2');
}`;
document.head.append(style);
// end only for demo

const text = document.querySelector('text');
console.log('before', text.getComputedTextLength());

document.fonts.ready.then(() => {
  console.log('after', text.getComputedTextLength());
});
text {
  font-family: 'Shadows Into Light', monospace;
  font-size: 30px;
}
<svg>
  <text y="60">Hello world</text>
</svg>

如果您希望在页面加载后添加字体,则可以使用 document.fonts.load方法:

const text = document.querySelector('text');
document.fonts.ready.then(() => {
  console.log('font.ready fires too soon');
});

document.addEventListener('click', e => {
  document.fonts.load("30px 'Shadows Into Light'")
    .then(() => {
      console.log('at font load', text.getComputedTextLength());
    });
  text.classList.add('use-font');
  console.log('before', text.getComputedTextLength());
}, {once: true});
@font-face {
  font-family: 'Shadows Into Light';
  src: url("https://fonts.gstatic.com/s/shadowsintolight/v7/UqyNK9UOIntux_czAvDQx_ZcHqZXBNQzdcD55TecYQ.woff2") format('woff2');
}
text.use-font {
  font-family: 'Shadows Into Light';
}
text { font-size: 30px; }
<svg>
  <text y="60">Click to change the font</text>
</svg>

关于javascript - SVG 文本元素的就绪事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57503616/

相关文章:

javascript - 基于光标位置的背景颜色、特定色谱

javascript - 如何使用悬停效果更改文本

javascript - 循环动画javascript,SetInterval只工作一次

javascript - 如何在其他函数中获取选项id

JavaScript 什么也不做

java - 如何让 Android Studio 从 svg 文件自动创建 Vector drawable?

javascript - 获取周围 div 的类(Javascript、jquery)

Javascript,jQuery : Change a certain word of a div into a <span> with a function

html - 使用 CSS3 自定义形状和动画

html - 为什么我不能在我的 svg 路径上添加边框?