Konva - icons from web fonts like Font Awesome
Photo by Harpal Singh / Unsplash

Konva - icons from web fonts like Font Awesome

In canvas apps we need to make buttons and use icons for other purposes. Font Awesome and its fellows are often selected by the boss as a critical requirement. They're easy to use with HTML elements and CSS, but what about the HTML5 canvas? Here's a way...

TLDR: There's a working demo CodePen here.

The Mission

Show an icon on the canvas that displays an icon from FontAwesome - for example the plug plug icon.

The solution

The answer is to let the browser load the font, have it set up an icon element, then read the icon info from that element. Note that these icons are actually created as text, so what we're getting is actually a text glyph.

Essentially what we do is create an <i> element, set its config to show the required icon, then read the style attributes of interest and return them to be set as a Konva.Text shape's attributes. Here's the code for the function that gets the good stuff.


function loadIcon(className) {

  // make an HTML icon element. You could recycle one of these.
  const i = document.createElement("i");

  // position out of view before we add to the page. 
  i.style.position = "absolute"
  i.style.left = '-1000px'
  
  // set the class - something like "fas fa-plug"
  i.setAttribute("class", className);

  // gotta add to the page to get lazy browsers to bother loading it!
  document.body.appendChild(i);

  // Because of how FA sets its elements with _before_ we get font 
  // info from the _i_ element and icon from the _before_ element.
  // You might need to check this approach if you use another icon
  // library.
  const iStyles = window.getComputedStyle(i),
        iBeforeStyles = window.getComputedStyle(i, ":before"),
        fontFamily = iStyles.getPropertyValue("font-family"),
        fontWeight = iStyles.getPropertyValue("font-weight"),
        icon = String.fromCodePoint(
          iBeforeStyles.getPropertyValue("content").codePointAt(1)
        );

  // Cleanup the icon element.
  i.remove();

  // Return an object with keys matched to Konva attr names. 
  // Back in the caller just do konva.text.setAttrs(return val)
  return {
    fontStyle: fontWeight,
    fontFamily: fontFamily,
    text: icon
  };
}

Summary

We've seen an approach to getting Font Awesome icons into Konva as text in a Konva.Text shape. Once there we can vary all of the usual properties, grab images, etc. The approach should be adaptable for other icon libraries that operate in the same way. Don't worry too much about how they get their icons into the HTML element, just follow their getting started info then when you can see the icon in the HTML element, unleash this technique. Good luck.

Thanks for reading.

VW. Mar 2025