Skip to content

Registering fonts after drawing on canvas seems to work fine? #1921

Closed

Description

@jhuckaby

Documentation Issue?

The docs state (note emphasis):

To use a font file that is not installed as a system font, use registerFont() to register the font with Canvas. This must be done before the Canvas is created.

However, going against the docs and loading the font after creating and drawing into the canvas seems to work just fine for me. My code:

var fs = require('fs');
var Canvas = require('canvas');
var canvas = Canvas.createCanvas(640, 100);
var ctx = canvas.getContext('2d');

ctx.strokeStyle = 'gray';
ctx.fillStyle = 'yellow';
ctx.beginPath();
ctx.rect( 50, 10, 300, 80 );
ctx.fill();
ctx.stroke();

Canvas.registerFont(('futurastd-m.otf'), { family: 'FuturaStdMedium' });

ctx.font = 'normal normal 36px FuturaStdMedium';
ctx.fillStyle = 'black';
ctx.fillText('Now is the time for all good men.', 10, 35);

canvas.createPNGStream().pipe(fs.createWriteStream('output.png'));

Output:

output-joe

This renders correctly. I guess I was expecting it to crash or something? My question is, is this just a documentation issue? Was the requirement a previous limitation with node-canvas v1 perhaps, now gone with v2?

Your Environment

  • Version: node-canvas HEAD revision, compiled from source 2021/11/03 (reported version: 2.8)
  • Environment: CentOS Linux release 7.7.1908 (Core)

Activity

  1. jhuckaby commented on May 25, 2022

    @jhuckaby
    ContributorAuthor

    Update: This has now started to fail (font renders as some kind of generic default) with canvas v2.9.1, when the font is registered after the canvas is created.

    Examples:

    canvas v2.9.0 (correct font):

    output-2 9 0-linux

    canvas v2.9.1 (incorrect font):

    output-2 9 1-linux

    So I guess now the order really matters... at least on Linux. macOS doesn't seem to care.

  2. added a commit that references this issue on Jan 15, 2025
    56635e5
  3. chearon commented on Jan 15, 2025

    @chearon
    Collaborator

    It's been a while since you asked, but the answer is that Pango caches all fonts present on the OS in a FontMap. When you register a custom font, we change the default FontMap, but we don't update the PangoContext stored on the canvas to use that new FontMap. (I'm not sure how it could have worked before. Maybe Pango used to do something differently?).

  4. added 3 commits that reference this issue on Jan 15, 2025
    ae521f4
    803333c
    a26db48
  5. added a commit that references this issue on Jan 18, 2025
    88e9657
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions