我正在使用fabric-js在画布上创建模板。但面临有线问题。
我在画布上添加了一个Textbox
对象,当我尝试更改Textbox
的 fontFamily 和 fontWeight 时,有时textBackgroundColor没有涵盖整篇文章。
我创建了一个jsfiddle来展示这个问题。
Merriweather
更改为Lato
normal
更改为bold
注意:对于
Merriweather
等特定字体而言,这种情况正在发生 所有,有时它有效但不是每次都有效。
答案 0 :(得分:1)
当字体未正确加载时会发生这种情况。 fabricJs请求字体粗体,即未准备好,甚至常规字体都没有准备好,并使用回退进行渲染。 当字体准备就绪时,字体测量已经完成,并且是错误的。
您必须使用字体加载器正确加载字体。 检查fontFaceObeserver,真的很容易使用。
在下面的代码片段中,我只使用了一个非常hacky的setTimeout和2段来强制浏览器提前加载字体。
var canvas = new fabric.Canvas('canvas');
setTimeout(function() {
text = new fabric.Textbox("Click here twice to edit", {
width: 300,
fontSize: 25,
fontFamily: 'Merriweather',
textAlign: 'center',
textBackgroundColor : '#000',
fill: '#ffc107',
});
canvas.add(text);
window.toggleBoldText = function() {
var obj = canvas.getActiveObject();
if(obj){
if (obj.get('fontWeight') == 'normal'){
obj.set('fontWeight', 'bold');
}else{
obj.set('fontWeight', 'normal');
}
canvas.renderAll();
}else{
alert("select text object to add font weight");
}
}
window.toggleFontFamily = function() {
var obj = canvas.getActiveObject();
if(obj){
if (obj.get('fontFamily') == 'Merriweather'){
obj.set('fontFamily', 'Lato');
}else{
obj.set('fontFamily', 'Merriweather');
}
canvas.renderAll();
}else{
alert("select text object to add font family");
}
}
}, 3000);

@import url(//fonts.googleapis.com/css?family=Merriweather%7CLato);
.canvas-container {
border: 1px dotted #ccc;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.js"></script>
<button onclick="toggleFontFamily()">toggle font family</button>
<button onclick="toggleBoldText()">toggle bold</button>
<span style="font-family: Merriweather; font-weight: bold;">Merri bold</span><span style="font-family: Merriweather; font-weight: normal;">Merri normal</span>
<canvas width="500" height="300" id="canvas"></canvas>
&#13;
答案 1 :(得分:0)
有同样的问题,但我创建了带有选项的选择元素,用户可以在其中选择他需要的字体。在我不在选择选项上使用字体样式之前,但经过几个小时的谷歌搜索后,我意识到只需将该字体添加到列表中即可下载字体。
之后fabricjs 工作得很好