Data

Find and replace fonts

Try it in the demo →

A design usually pairs a few fonts: one for headlines, one for body text, sometimes a third for details. getUsedFonts lists the families a text box uses, and replaceFonts swaps one family for another everywhere in the box with one call, including single words set in that family inside a sentence. Families you don't name keep their place.

List the fonts a box uses

headline.getUsedFonts(); // ["Playfair Display", "Poppins"]

getUsedFonts lists each family once: every paragraph's family and every run's own. A paragraph's family is listed even when each of its runs sets another, because new text typed in that paragraph takes it.

Replace fonts

headline.replaceFonts([
  { from: "Playfair Display", to: "Fraunces" },
  { from: "Poppins", to: "Montserrat" },
]);
  • Each from is matched exactly, as the document spells the family, in paragraphs and in runs.
  • Bold, italic, weights and sizes are kept. A weight the new family lacks is drawn in a weight the family has.
  • The box keeps its width, and the call is one undo step.
  • A family the page does not have yet is fetched, and the box lays itself out again when it arrives. To change fonts without a moment in a stand-in font, load them first with loadFonts.

Keep the text in its space

A new font can be wider or taller than the old one. Pass containerHeight to shrink the type, if it must, to fit that height after the swap, as Shrink to fit does:

await loadFonts(["Fraunces"]);
headline.replaceFonts([{ from: "Playfair Display", to: "Fraunces" }], { containerHeight: 128 });

The fit is measured with the fonts already loaded, which is why the example loads Fraunces first. The fit and the swap are one undo step together.

Change the fonts of a whole design

Each box has its own fonts, so call replaceFonts on each box. Each box's call is its own undo step.

const pairing = [
  { from: "Playfair Display", to: "Fraunces" },
  { from: "Poppins", to: "Montserrat" },
];

// Konva
for (const box of rt.manager.boxes()) box.replaceFonts(pairing);

// Plain canvas
for (const box of rt.boxes()) box.replaceFonts(pairing);

To change the font of selected text or a selected box, use setFontFamily instead - see Fonts.

In the API reference