Fabric.js uses custom fonts

Introduction to this article

Like + Follow + Collection = Learned

If you use Fabric.js for editing products, you may need to configure fonts for users.

This time I will talk about how to use custom fonts when creating text in Fabric.js, how to modify fonts when the project is running, and recommendations A tool to simplify the font library.

Before studying this article, you must have some basic knowledge of Fabric.js. If you have not understood Fabric.js, you can read “Fabric.js from entry to expansion”

Set font when creating text

When using a custom font library in Fabric.js, you need to use the fontfaceobserver.js tool. As for why, we will talk about it later.

To set the font when creating text, you need to do the following steps:

  1. Introduce fonts in CSS.
  2. Use Fabric.js to create the canvas.
  3. Wait until the font is loaded before setting the text font.
  4. Add text to the canvas.

In this example, I’m using IText to create the text, and I can set a custom font at creation time via its fontFamily property.

Let’s take a look at the effect of this example first

file

I use Douyu’s fonts. I heard that they can be used for free. I hope you didn’t lie to me~

Follow the steps mentioned earlier to achieve this:

<style>
  /*Introduce Douyu font */
  /* I put the font locally, you need to modify the font path according to your own project */
  @font-face {
    font-family: douyu;
    src: url('../../fonts/douyu.ttf');
  }
</style>

<!-- Canvas element -->
<canvas id="c" width="300" height="300" style="border: 1px solid #ccc"></canvas>

<!-- Introduce fontfaceobserver.js and fabric.js -->
<script src="../../script/fontfaceobserver.js"></script>
<script src="../../script/fabric.js"></script>

<script>
    //Create canvas
    const canvas = new fabric.Canvas('c')

  // Monitor Douyu font loading
  const douyuFont = new FontFaceObserver('douyu')

  // Wait until the font loading is completed or fails before executing the font setting function
  douyuFont.load()
      // Loading successful
    .then(() => {
        //Create text
        const iText = new fabric.IText('Thunder Monkey', {
          fontFamily: 'douyu' // Set font
        })
      //Add text to canvas
      canvas.add(iText)
      })
      // Failed to load
      .catch(() => {
        console.error('Font loading failed')
      })
</script>

Because the font is a resource file, referencing the resource file takes time to load.

Creating a canvas to render text may be much faster than loading font resources, so you need to use fontfaceobserver.js to monitor the font loading results.

  • fontfaceobserver.js official website
  • fontfaceobserver.js github address

For detailed usage of fontfaceobserver.js, please click on the official website above.

Simple usage is as follows:

<style>
  @font-face {
    font-family: custom font name;
    src: url('Font package path');
  }
</style>

<script>
const font = new FontFaceObserver('custom font name')

font.load()
  .then()
  .catch()
</script>

The function of the load() method is to monitor the font loading result. If the loading is successful, the then code will be executed. If the loading fails, the catch code will be executed.

Dynamic font modification

If you need to dynamically modify the font while the project is running, you need to do the following steps:

  1. Load the font library you want to use in advance.
  2. Create canvas.
  3. Wait until the font is loaded before setting the text font.
  4. Add text to the canvas.
  5. Before modifying the font, first obtain the text element to be modified.
  6. Use the set method to set the text’s fontFamily property.
  7. Refresh the canvas.

This example uses fonts from Douyu and Alibaba. I checked and they said they are free to use.

file

Hands-on coding according to the steps mentioned above

<style>
  /* I put the font locally, you need to modify the font path according to your own project */
  /*Introduce Douyu font */
  @font-face {
    font-family: douyu;
    src: url('../../fonts/douyu.ttf');
  }
  /*Introduce Alibaba fonts */
  @font-face {
    font-family: ali;
    src: url('../../fonts/AlibabaPuHuiTi-2-35-Thin.ttf');
  }
</style>

<!-- Button to set font -->
<button οnclick="setFont('douyu')">Douyu</button>
<button οnclick="setFont('ali')">Ali</button>

<!-- Canvas element -->
<canvas id="c" width="300" height="300" style="border: 1px solid #ccc"></canvas>

<!-- Introduce fontfaceobserver.js and fabric.js -->
<script src="../../script/fontfaceobserver.js"></script>
<script src="../../script/fabric.js"></script>

<script>
    //Create canvas
    const canvas = new fabric.Canvas('c')
  //Create text
  const iText = new fabric.IText('Thunder Monkey')
  //Add text to canvas
  canvas.add(iText)

  //Set font
  function setFont(font) {
    // Monitor the loading status of the font currently to be set
    let fontFamily = new FontFaceObserver(font)

    // Execute after loading is complete
    fontFamily.load()
        // Loading successful
      .then(() => {
        let target = canvas.getActiveObject()
        if (target) {
          target.set("fontFamily", font)
          canvas.requestRenderAll()
        }
      })
        // Failed to load
      .catch(() => {
        console.error('Font loading failed')
      })
  }
</script>

Simplified font library

I have finished talking about how to use the custom font library in Fabric.js, but I still encounter a problem in my daily work: some special fonts are used in certain places, such as numbers, project names, etc. .

Usually the font library contains a large number of fonts, but in the actual project only a few words may use special fonts.

After my long interrogation, an anonymous netizen finally revealed the tool he used to streamline the font library

file

file

Fontmin has a client, and you can also use the terminal to operate it directly.

The client also provides two versions of mac and windows, which is very simple to operate. Workers in need can open the link to obtain it.

  • Fontmin official website
  • Fontmin github address

code warehouse

The complete code for this article can be obtained through the link below.

? Fabric.js uses custom fonts

“Fabric.js from entry to _ _ _ _ _ _”

《What should I do if the Fabric.js style is not updated? 》

《Fabric.js Custom Control》

“Fabric.js explains the official demo: Stickman”

“Fabric.js dragging vertices to modify polygon shapes”

《Fabric.js copy and paste elements》

Like + Follow + Collection = Learned Code Warehouse