0

I have a react project and hosted the fonts by myself following this guide

my folders looks like this:

src
|___fonts
|   |___css
|   |   |___fontawesome.css
|   |   |___regular.css
|   |___webfonts
|       |___fa-regular-400.woff2
|       |___fa-regular-400.ttf
|___App.css
|___App.ts
|___...

And in my App.js i have the following code:

import React, {useLayoutEffect, useRef} from 'react';
import './App.css';
import './fonts/css/fontawesome.css';
import './fonts/css/regular.css';
function App() {

  const canvasRef = useRef<HTMLCanvasElement>(null);
  let ctx: CanvasRenderingContext2D;
  let canvas: HTMLCanvasElement;
  useLayoutEffect(() => {
    canvas = canvasRef.current as HTMLCanvasElement;
    ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
    draw();
  }, []);

  const draw = (): void => {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.font = '100px Font Awesome 6 Pro';
    ctx.fillText('\uf111', 100, 100);
    requestAnimationFrame(draw);
  }

  return (
    <div className="App">
      <canvas id={'game_canvas'} ref={canvasRef} width={500} height={500}>Your browser doesn't support canvas.</canvas>
      <p>&#xf111;</p>
    </div>
  );
}

export default App.ts;

and inside App.css

.App {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: 'Font Awesome 6 Pro';
}
.App #game_canvas {
  border: 1px solid red;
}

Note that after the canvas i'm rendering a <p></p> tag. That tag is using the HTML syntax for unicode, while in the ctx.fillText function i'm using the other syntax.

The result is I see the icon rendered in the <p></p> tag but not the icon inside the canvas context.

Inside canvas the icon is broken, but the fa-circle-icon can be seen outside

I tried alternating into several syntaxes for unicode, and also integrating the typography with Styled components following this guide with no good results.

The expected behavior is to be able to render an icon from a self hosted webfont inside a canvas 2D context.

  • Don't forget to clean up your `requestAnimationFrame` in the useEffect return. – ggorlen Jan 03 '23 at 03:57
  • @ggorlen Thanks for the heads up! I modified the code to return a function that calls cancelAnimationFrame in the useLayoutEffect – user8922252 Jan 03 '23 at 04:20

1 Answers1

0

Found the issue!, I simply forgot the double quotes in the font name defining the ctx.font property

ctx.font = '100px Font Awesome 6 Pro' //wrong
ctx.font = '100px "Font Awesome 6 Pro"' //correct

Found the issue while looking closely at this: How can I use FontAwesome icons on a html 5 canvas