Issue with font selection in Fabric.js

I am currently working with fabric js version 1.7.22 alongside angular 7 to create a text editor. I have encountered an issue when trying to add text to the canvas using a custom font as shown in the code snippet below.

var canvas= new fabric.Canvas('c');
var junction_font = new FontFace('3d.demo', 'url(https://fonts.gstatic.com/s/bethellen/v1/WwkbxPW2BE-3rb_JNT-qIIcoVQ.woff2)');
junction_font.load().then(function (loaded_face) 
{
  console.log('loaded.font', loaded_face);
  document['fonts'].add(loaded_face);
  var text = new fabric.IText("lazy dog jumps over crystle guy.", {
    top: 10,
    left: 10,
    fontFamily: '3d.demo'
    })
  canvas.add(text);
  canvas.renderAll();
});

This code works perfectly fine with the latest version of fabric js 3.2.2, but it displays small text when used with fabric js version 1.7.22.

Unfortunately, my entire project is based on the older version and I cannot update it at this time.

I have tried searching extensively on Google to find a solution for this issue, but so far I have been unsuccessful.

Is there any Patch available to resolve this problem and support all kinds of font names? Any help would be greatly appreciated.

For a demonstration of the issue, you can refer to this fiddle:https://jsfiddle.net/Mark_1998/pxr9yz7g/

Answer №1

If your font is working perfectly but you are experiencing issues with the font size, please refer to the code below. If the font is not working at all, please inform me so I can update the code.

var text = new fabric.IText('The lazy brown fox jumps over the quick dog.',{
                left: 10,
                top: 10,
                fontFamily: '3d.demo',
               fill: '#fff',
               stroke: '#000',
               strokeWidth: .1,
               fontSize: 36,
            });
            canvas.add(text);
             canvas.renderAll();

If you encounter problems with your font family, consider using Google Fonts instead. See the code below for guidance.

Add this at the top of your page:

<link href='https://fonts.googleapis.com/css?family=Poppins|Roboto|Oswald|Arial|Lobster|Pacifico|Satisfy|Bangers|Audiowide|Sacramento' rel='stylesheet' type='text/css'>

 var text = new fabric.IText('The lazy brown fox jumps over the quick dog.',{
                    left: 10,
                    top: 10,
                    fontFamily: 'Arial',
                    fill: '#fff',
                    stroke: '#000',
                    strokeWidth: .1,
                    fontSize: 36,
                });
                canvas.add(text);
                canvas.renderAll();

Answer №2

After extensive searching on Google, I discovered that fontFace does not support certain types of strings as the first parameter. Therefore, I have provided a solution to assist other developers.

The following pattern of font family does not render correctly in fabric js: e.g. new FontFace("exo 2", font_path);

In this example, the font family name is "exo 2"

  1. It is not valid if it ends with a number word, meaning the last character is a number followed by a space
  2. It is not valid if it starts with any word containing a number
  3. It is not valid if the name contains any dots
  4. It is not valid if the name starts with a number

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The reflow feature in Highcharts does not properly update the width of the container for High

I am currently working on adjusting the width of Highcharts dynamically to fit its parent container. To achieve this, I have set up a mechanism that listens to changes in the sidebar state and triggers a reflow function whenever the state is altered. useEf ...

Tips for dividing the elements of an array by 4 using Javascript or ReactJS

I have a large array of items that I need to organize into 4 sections in order to improve the display on my user interface. The array contains up to 20 objects, and my objective is to create 4 separate arrays each containing 5 objects. let attributes = [ ...

Leverage the power of multiline JavaScript expressions within your React components

I am facing a situation where I have the following React function component source code: return ( result.map(item => ( <tr key={item.id}> <td> {new Date(item.pub_date).getFullYear()} / {new Date(item.pub_date).getMont ...

another solution instead of using several try-catch blocks within a function

Consider a scenario where we define a function as shown below: async function doSomethingWithFriends() { let user, friends, friendsOfFriends = null; try { user = await getUser(); } catch(err){ return [401, err] } try { ...

Changing the tooltip background color in FullCalendar 6 and Bootstrap 5: A step-by-step guide

My FullCalendar agenda displays events with colored backgrounds. However, I want the tooltips for these events to have matching background colors as well. Currently, the tooltips always show up with a black background. Is there a way to dynamically change ...

Using JavaScript to set attribute values in Python Selenium, these values are cleared after each update

Assuming : for i in list('{}'.format(value)): self.browser.execute_script( "arguments[0].setAttribute('value', '{}');".format(i.replace('&b ...

Finding a specific document in MongoDB using a unique slug within Next.js: A step-by-step guide

I have a collection of data in MongoDB structured like this: [ { "Post": "this is a post", "_id": ObjectId("630f3c32c1a580642a9ff4a0"), "slug": "this-is-a-title", "title" ...

Creating visual representations of class, organization, flow, or state diagrams using Vega or Vega-lite

I'm struggling to find an example of a state, class, flow chart, or org chart diagram created with Vega. Are there any available online? Vega seems like the perfect tool for this type of visualization, although it may be a bit complex. Without a star ...

Customize the background color of InfoBox in Google Maps API V3 using a dropdown menu

I'm attempting to dynamically change the background color of an InfoBox by using a Dropdown list (this InfoBox is used to create map labels). I am using google.maps.event.addDomListener, but the values are not returning. Below is my code, can anyone i ...

The ::before pseudo element is malfunctioning when used in the makeStyles function

I am currently utilizing the makeStyles function in React, but I seem to be facing an issue where the content within the ::before pseudo-element is not displaying. Strangely enough, when the content is an image it works fine, but text does not render. Jus ...

How can I generate codegen types using typeDefs?

I have been exploring the capabilities of graphql-codegen to automatically generate TypeScript types from my GraphQL type definitions. However, I encountered an issue where I received the following error message: Failed to load schema from code file " ...

I have been seeking the perfect solution to seamlessly incorporate ckeditor5 with comments in my AngularJS applications. Despite extensive research, I have not come across any angularjs-specific plugins for this purpose. It

import Comments from '@ckeditor/ckeditor5-comments/src/comments'; ClassicEditor.builtinPlugins = [ Essentials, Paragraph, Bold, Italic, Image, Comments ]; I am trying to figure out how to incorporate comments into the CKEditor5 in an AngularJS ...

Attempting to manipulate the selected tab material using a custom directive with two-way data binding

I've been struggling to change the tab using code and can't seem to figure out what's causing the error. It works fine when I use the controller to change the variable, but when trying to bind it through a directive, it breaks. var app = an ...

What is the best way to transform React API data into props that can be utilized in different components?

I've been struggling with this issue for quite some time now, unable to understand how to manipulate the data in a way that allows me to use it in other components. Although I can display the data correctly, I'm advised to structure it within a f ...

What is the best way to transmit a response from PHP to Ajax?

A JavaScript function is used here that utilizes the POST method to send form data to PHP. The PHP script then checks this data in a database to verify its authenticity. However, there seems to be confusion on how to convey the response from PHP back to Ja ...

There are occasional instances in Angular 6 when gapi is not defined

I am currently developing an app with Angular 6 that allows users to log in using the Google API. Although everything is working smoothly, I encounter a problem at times when the 'client' library fails to load and displays an error stating gapi i ...

Issue: missing proper invocation of `next` after an `await` in a `catch`

I had a simple route that was functioning well until I refactored it using catch. Suddenly, it stopped working and threw an UnhandledPromiseRejectionWarning: router.get('/', async (req, res, next) => { const allEmployees = await employees.fi ...

How to capture the "chip close" event in Vuetify

Exploring the vuetify realm as a newcomer, I find myself grappling with event handling while working on my first web app project. Specifically, I am currently developing a "UserPicker" component using VAutocomplete. This component functions by sending an ...

Utilize Google Sheets to extract information from a web address containing quotation marks

I am currently utilizing a script called "ImportJSON" developed by paulgambill https://gist.github.com/paulgambill/cacd19da95a1421d3164 The URL I am working with contains quotes characters For instance: http://SomeAPIULR?{"Type": "SomeType"}&APIKE ...

Using Vue.js to bind data in two directions by using an object with v-for

I can't seem to get input data properly bound to object properties. When I try to iterate through an object to create input fields based on its attributes, the v-model data binding doesn't seem to be working as expected. Even with the code below, ...