我正在使用 fabric-js用于在 Canvas 上创建模板。但面临有线问题。
当我尝试更改 Textbox
的 fontFamily 和 fontWeight 时,我已经在 Canvas 上添加了一个 Textbox
对象>,有时 textBackgroundColor 不会覆盖整个文本。
我创建了一个 jsfiddle来展示这个问题。
重现步骤:
- 选择文本框对象,将 fontFamily 从
Merriweather
更改为Lato
- 然后将 fontWeight 从
normal
更改为bold
Note: it is happening for specific fonts like
Merriweather
not for all, Also sometimes it works but not everytime.
最佳答案
当字体未正确加载时会发生这种情况。 fabricJs 请求粗体字体,这还没有准备好,即使是常规字体也没有准备好,并使用后备渲染。 当字体准备好时,字体测量已经完成,并且是错误的。
您必须使用字体加载器正确加载字体。 检查 fontFaceObeserver,真的很容易使用。
在下面的代码片段中,我只使用了一个非常 hacky 的 setTimeout 和 2 paragraph 来强制浏览器提前加载字体。
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>
关于javascript - fabric-js textBakgroundColor 在更改对象属性时不覆盖整个文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48485058/