custom font with fabric.js version 1.7.22
by Andrea Bogazzi
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js"></script>
<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>
<head>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
</head>
<style>
@media screen and (-webkit-min-device-pixel-ratio:0) {
#canvas {
font-smoothing: antialiased;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
}
</style>
<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("VAVAVAVAVAVAVAVAV", {
left: 210,
top: 261,
fontSize: 69,
width: 635,
textAlign: 'left',
fontWeight: 'bold',
fill: 'black',
charSpacing:0,
strokeWidth: 0,
stroke: '#ffffff',
hasRotatingPoint: true,
isLocked: false,
shadow_theme_index: undefined,
});
font.load().then(function() {
fabric.util.clearFabricFontCache(font_family);
console.log("loaded")
Text.set("fontFamily", font_family);
Text.set('dirty', true);
canvas.add(Text);
canvas.requestRenderAll();
}).catch(function(e) {
console.log(e)
/* alert('font loading failed ' + font_family) */;
});