我正在使用 Fabric JS 开发一个大型自定义应用程序,我已经做得很好了。但是我对使用 webfont 的初始化加载文本对象有疑问。
只要该字体在客户端计算机上是本地的,我就可以正常工作,否则不会加载网络字体,并且 Canvas 上的文本对象会以默认的无衬线字体系列呈现。
简而言之,这是我所做的(在这个例子中我使用“allstar”作为我的网络字体):
CSS: css 在 fabric.js 之前加载到头部的 fonts.css 中
@font-face{
font-family:'allstar';
src:
url('/path-to-fonts/all_star-webfont.eot');
src:
url('/path-to-fonts/all_star-webfont.eot?#iefix') format('embedded-opentype'),
url('/path-to-fonts/all_star-webfont.woff') format('woff'),
url('/path-to-fonts/all_star-webfont.ttf') format('truetype'),
url('/path-to-fonts/all_star-webfont.svg#allstarregular') format('svg');
font-weight:normal;
font-style:normal
}
Javascript: 在 $(document).ready(function(){}) 内的页面底部加载
var textSample = new fabric.Text(text, {
fontFamily: "allstar",
});
canvas.add(textSample);
canvas.renderAll();
如果我在页面的其他地方使用该字体(例如:在带有点的透明跨度标签中并加载了字体),它工作正常。但我认为这不是正确的编码方式。
我使用 fabric.js 版本 1.3.0
最佳答案
问题:
- Canvas 立即呈现
- Google 加载网络字体
- Canvas 在下一个重新渲染它的事件之前不知道
解决方法:
- Canvas 立即呈现
- Google 通过回调加载网络字体
- 你强制渲染
- Canvas 现在有
WebFontConfig = {
google: { families: [ 'Ribeye::latin', 'Lora::latin', 'Croissant+One::latin', 'Emblema+One::latin', 'Graduate::latin', 'Hammersmith+One::latin', 'Oswald::latin', 'Oxygen::latin', 'Krona+One::latin', 'Indie+Flower::latin', 'Courgette::latin', 'Ranchers::latin' ] }
};
(function() {
var src = ('https:' === document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
$.getScript(src, function(data) {
// Not sure why I need to run this twice but it makes it load the font and then reposition the font to it's correct coords.
canvas.renderAll();
canvas.renderAll();
});
})();
关于javascript - 在 Fabric.js 中使用远程网络字体初始化加载文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19927393/