textbox with custom font
by Andrea Bogazzi
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/webfont/1.6.28/webfontloader.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fontfaceobserver/2.0.4/fontfaceobserver.standalone.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js"></script>
<head>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400&display=swap" rel="stylesheet">
</head>
<canvas id="canvas" width="1000" height="1000"></canvas>
JavaScript
var canvas = new fabric.Canvas("canvas");
fabric.Object.prototype.objectCaching = false;
var font_family = "Roboto";
var font = new FontFaceObserver(font_family);
var Text = new fabric.Textbox("ADD HEADING TEXT", {
left: 210,
top: 261,
fontSize: 69,
width: 635,
textAlign: 'left',
fontWeight:'bold',
fill: 'black',
charSpacing:0,
strokeWidth: 0,
stroke: '#ffffff',
shadow: {
"color": "#000000",
"blur": 0,
"offsetX": 0,
"offsetY": 0,
"affectStroke": false,
"caching":false,
"inCompositionMode":true
},
hasRotatingPoint: true,
isLocked: false,
shadow_theme_index: undefined,
});
font.load().then(function() {
fabric.util.clearFabricFontCache(font_family);
Text.set("fontFamily", font_family);
Text.initDimensions();
canvas.add(Text);
canvas.requestRenderAll();
}).catch(function(e) {
console.log(e)
alert('font loading failed ' + font_family);
});